I'm facing an issue with my Google map. I have a data array that is dynamically returned, and I want to use it to add markers to the map. However, the markers don't work when I pass the data variable to the add_markers() function. It only works if I directly input the data into the function. Why is this happening and how can I resolve it?
function RelatedLocationAjax() {
var lat = $( "#lat" ).val();
var lng = $( "#lng" ).val();
var srv = $( "#ServiceId" ).val();
var data = [
["john","Do this service 1 <a href=''>more</a>", "29.957051,30.914529", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
["peter", "Do this service 1 <a href=''>more</a>", "29.956051,30.913529", "http://maps.google.com/mapfiles/ms/icons/green.png"],
["sara","Do this service 1 <a href=''>more</a>","29.955051,30.912529", "http://maps.google.com/mapfiles/ms/icons/red.png"],
];
$.ajax({
type: "POST",
url: "<?= base_url() ?>services/closest_locations",
data:"data="+ '{ "latitude":"'+ lat+'", "longitude": "'+lng+'", "ServiceId": "'+srv+'" }',
success:function(response) {
// When passing the data array to add_markers, it doesn't work
add_markers(response);
}
});
}
function add_markers(data){
var marker, i;
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
document.getElementById('info').innerHTML = "found " + data.length + " data<br>";
for (i = 0; i < data.length; i++) {
var coordStr = data[i][2];
var coords = coordStr.split(",");
var pt = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
bounds.extend(pt);
marker = new google.maps.Marker({
position: pt,
map: map,
icon: data[i][3],
address: data[i][1],
title: data[i][0],
html: data[i][0] + "<br>" + data[i][1]
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {infowindow.setContent(marker.html);
infowindow.open(map, marker);
}
})
(marker, i));
}
map.fitBounds(bounds);
}