简体   繁体   中英

Google maps Javascript API V3 : Markers have same title

I'm having a hard time with Google Maps API V3. I am able to display several markers on my map (3 markers) but every markers have the same title (Maurice GENEVOIX). Are you able to help me/tell me how ? I can't figure it. I have the code below :

function initialize() {
    var myMarker=null;
    var i=0;
    var GeocoderOptions;
    var myGeocoder;
    var nom;
    var temp;
    var info = [
    ['57 Avenue Joseph Kessel 78180 Montigny-le-Bretonneux','Paul VERLAINE'],
    ['24 Rue du champ d avoine 78180 Mintigny-le-Bretonneux','Pauline VERLAINE'],
    ['21 Rue du Poirier Saint Martin 78180 Mintigny-le-Bretonneux','Maurice GENEVOIX']
    ];

    var mapOptions = {
      center: new google.maps.LatLng(48.772, 2.028),
      zoom: 14,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

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

        function GeocodingResult( results , status , i)
        {


            if(status == google.maps.GeocoderStatus.OK){

                myMarker = new google.maps.Marker({
                    position: results[0].geometry.location,
                    map: map,
                    title: nom,
                    icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png'
                }); 

            } else {
                alert("L'adresse n'a pas pu etre geocodee avec succes.");
            }
        }

    for(i=0;i<info.length;i++){ 
    GeocoderOptions={
        'address' : info[i][0],
        'region':'FR'       
    };

        nom=info[i][1];

        myGeocoder = new google.maps.Geocoder();
        myGeocoder.geocode( GeocoderOptions, GeocodingResult );

    }

  }
  google.maps.event.addDomListener(window, 'load', initialize);

This is a JavaScript closure issue, rather than an issue with the Google Maps JS API. Here's how you should define the callback, so you can get the correct value for i . (I took the liberty of taking your GeocodingResult function and inlining it.)

DEMO

myGeocoder.geocode( GeocoderOptions, function(i){
    return function(results, status){
    if(status == google.maps.GeocoderStatus.OK){
        markers.push( new google.maps.Marker({
            position: results[0].geometry.location,
            map: map,
            title: info[i][1],
            icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png'
        })); 

    } else {
        alert("L'adresse n'a pas pu etre geocodee avec succes.");
    }
}
}(i)); // this sends the current i into the closure of 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