Dynamic Markers - Google Maps API - Markers not incrementing with i value in loop

后端 未结 1 1318
灰色年华
灰色年华 2021-01-25 04:48

I have created the maps api below and have an array of addresses that come from a database. The map loads correctly, however I have the following issue.

  1. The d

相关标签:
1条回答
  • 2021-01-25 05:36

    The old "function scope wrapper" trick (function(i) {...})(i) works here. Without it, the execution takes the final value of i. Also, if(i = 1) should be if(i == 1)

    To play around: http://jsfiddle.net/BK8vv/

    for (var i = 1; i < total; i++) {  
       (function(i) {
    
        // Use geocoder to grab latlong for user inputed address
        geocoder.geocode( { 'address': address[i]}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                // Redefine map center location
                if (i == 1){ map.setCenter(results[0].geometry.location); }
    
                // Create dynamic markers on map as per the address array
                        alert(i);
                var marker = new google.maps.Marker({
                    map: map, 
                    position: results[0].geometry.location,
                    title:address[i],
                    zIndex: i,
                    // PROBLEM CODE --- Using the function below it creates all Markers with a "1" instead of the "i" value..??  
                    icon: pinImage(i),
                    shadow: pinShadow
                });         
            }
           });
         })(i);
        }
    }
    
    0 讨论(0)
提交回复
热议问题