Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps Adding Markers dynamically

I want to add dynamic markers to my Map, where each is located at longitude[i] and latitude[i], and I want a pop-up window to open when the user click on the marker, where in the url of the window &id=id[i].

I tried using the following:

  <script type="text/javascript">
function initialize() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(48, 2),
mapTypeId: google.maps.MapTypeId.ROADMAP
};

var map = new google.maps.Map(document.getElementById('map-canvas'),
  mapOptions);

for (var i = 0; i < id.length; i++) {
var position = new google.maps.LatLng(latitude[i],longitude[i]);
marker[i] = new google.maps.Marker({
  position: position,
  map: map
});

marker[i].setTitle("pv");
google.maps.event.addListener(marker[i], 'click', function() {
window.open('blah.php?id='+id[i],'name','height=1000,width=1000')
});

}
}

google.maps.event.addDomListener(window, 'load', initialize);
  </script>

It doesn't seem to work, because the when clicking on the marker, the function addListener will be called and at the moment i = id.length

what I want is for marker[0] to open the window with id[0], id[1] for marker[1] etc...

like image 816
maggie Avatar asked Oct 22 '22 04:10

maggie


1 Answers

Can you try replacing this -

google.maps.event.addListener(marker[i], 'click', function() {
    window.open('blah.php?id='+id[i],'name','height=1000,width=1000')
});

by this -

(function (i) {
    google.maps.event.addListener(marker[i], 'click', function() {
        window.open('blah.php?id='+id[i],'name','height=1000,width=1000')
    });
})(i);

Wrapping the listener in a closure will execute it with the state at that point of time. Check this out for more details - adding 'click' event listeners in loop

like image 109
kinshukkar Avatar answered Oct 31 '22 14:10

kinshukkar