简体   繁体   中英

Google Maps API v3: Geocoding Reversal, only prints out one marker(javascript)

Made changes to the code putting depend data inside the function which returns a correct value to the infowindow instead of UNDEFINED.

Here comes the problem, only one marker is printed.

    var geocoder;
    var map; 

    function load() {
      geocoder = new google.maps.Geocoder();
      map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(57.699322, 11.951093),
        zoom: 6,
        minZoom: 6,
        maxZoom: 18,
        mapTypeId: 'roadmap'
      });
      var infoWindow = new google.maps.InfoWindow;

          // Get the xml data
    downloadUrl("functions.php", function(data) {
    var xml = data.responseXML;
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
        var point = new google.maps.LatLng(markers[i].getAttribute("lat"),markers[i].getAttribute("lng"));

        codeLatLng(point, function(addr){   
           var name = markers[i].getAttribute("name").replace("_"," ");
           var html = '<div class="markTitle">' + name.replace("_"," ") + '</div>'
                    + '<div class="markAddress">'+addr+'</div>'
                    + '<a class="markLink" href="http://www.wikiplace.se/index.php?title='+ name +'">'                      
                    +  'Läs mer om '+ name.replace("_"," ") + ' här...</a>';
           var marker = new google.maps.Marker({
                        map: map,
                        position: point,
                        uid: "id"+i});      
           google.maps.event.addListener(marker, 'click', function() {
                    infoWindow.setContent(html);
                    infoWindow.open(map, marker);});                 
        });   // end codeLatLng 

   }  // end for-loop
});// end downloadURL  
    }

This code seems to work.

  function codeLatLng(point, callback) {        
    geocoder.geocode({'latLng': point}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {     
          callback(results[1].formatted_address);
        } else {
          alert("Couldn't find address");
        }
      } else {
        alert('Geocoder failed due to: ' + status);
      }
    });     
  }

I've also checked the XML-file for errors but it's format is correct. Does anyone have a solution for this?

Thanks

codeLatLng is asynchronous, by the time you use addr it will still be undefined.

You should move the code that depends on its value being set to inside the callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM