Closing a Problem Using Listener and Google Maps Tags

I want to add a Listener event for each generated token, so when you click the token, you are redirected to the permalink URL. When using the code below, the permalink value is the same for each marker (it gets the last value). I read about closing issues, and that seems to be what I have. I really don't get the examples I looked at, though.

Can someone take a look at my code and point me in the right direction? Any help is much appreciated!

downloadUrl("http://localhost/map/generatexml.php", function(data) {
            var xml = parseXml(data);
            var markers = xml.documentElement.getElementsByTagName("marker");
            for (var i = 0; i < markers.length; i++) {
              var permalink = markers[i].getAttribute("permalink");
              var point = new google.maps.LatLng(
                  parseFloat(markers[i].getAttribute("lat")),
                  parseFloat(markers[i].getAttribute("lng")));
              var marker = new google.maps.Marker({map: map,position: point,icon: icon.icon,shadow: icon.shadow,title: name});
              google.maps.event.addListener(marker, 'click', function() {self.location.href = permalink;});
            }
+3
source share
3 answers

:

for (var i = 0; i < markers.length; ++i) {
  // ... like what you have already ...
  (function(permalink) {
    google.maps.event.addListener(marker, 'click', function() {self.location.href = permalink;});
  })(permalink);
}

"permalink" , .

+11

JavaScript , , var for, . , , var , , :

downloadUrl("http://localhost/map/generatexml.php", function(data) {
            var xml = parseXml(data);
            var markers = xml.documentElement.getElementsByTagName("marker");
            var i, permalink, point, marker;
            for (i = 0; i < markers.length; i++) {
              permalink = markers[i].getAttribute("permalink");
              point = new google.maps.LatLng(
                  parseFloat(markers[i].getAttribute("lat")),
                  parseFloat(markers[i].getAttribute("lng")));
              marker = new google.maps.Marker({map: map,position: point,icon: icon.icon,shadow: icon.shadow,title: name});
              google.maps.event.addListener(marker, 'click', function() {self.location.href = permalink;});
            }

click permalink , , for-loop.

: , , . , , .

+2

,

function AddInfoWidnow(marker,message)
{
     var infowindow = new google.maps.InfoWindow({ content: message });

     google.maps.event.addListener(marker, 'click', function() {

     infowindow.open(marker.get('map'), marker);

    }); 

}

To see a working sample, write here

+1
source

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


All Articles