I am trying to display markers on a Google Map from a PHP array containing lat & long values.
The PHP array looks like this at the moment:
Array
(
[0] => Array
(
[0] => 55.8490116, -4.222272800000042
[1] => 54.5979369, -7.274279400000069
)
[1] => Array
(
[0] => 55.8490116, -4.222272800000042
)
)
I then add this array to a JS array on the PHP like so:
<script type="text/javascript">
var markers = <?php echo $myarray; ?>;
</script>
And then in my JS for the map it looks like:
var infowindow = new google.maps.InfoWindow();
var marker, i;
var bounds = new google.maps.LatLngBounds();
console.log(markers);
for (i = 0; i < markers.length; i++) {
var pos = new google.maps.LatLng(markers[1][0]);
marker = new google.maps.Marker({
position: pos,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(markers[1][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
I am not sure where to go next. I know my my array does not mimic what is required by the Google Maps API, but not sure how I can change it to suit.
Thanks
Robert
I think the problem with your approach is in echoing the array.
The way I would try to fix it would be creating an empty array in JS called
markers, looping through all the values of the PHP array and then appending each of the values tomarkers.Also note that you have an array of arrays in PHP, so you’ll need a nested loop.
Please let me know if you need any code samples, or this would suffice.