Google Maps added markers dynamically

I want to add dynamic markers to my map, where each is in longitude [i] and latitude [i], and I want the pop-up to open when the user clicks 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> 

This does not work, because when you click on the marker, the addListener function is called and at the moment I = id.length

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

+4
source share
1 answer

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') }); 

this -

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

The listener wrapper in closure will execute it with the state at that point in time. Check this out for more information - adding a β€œclick” event listener in a loop

+3
source

Source: https://habr.com/ru/post/1494676/


All Articles