谷歌地图Javascript API V3:标记具有相同的标题

Google maps Javascript API V3 : Markers have same title

本文关键字:标题 API Javascript V3 谷歌地图      更新时间:2023-09-26

我在使用 Google Maps API V3 时遇到了困难。我能够在地图上显示多个标记(3 个标记),但每个标记都有相同的标题(Maurice GENEVOIX)。你能帮我/告诉我怎么做吗?我想不通。我有下面的代码:

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

这是一个JavaScript闭包问题,而不是Google Maps JS API的问题。下面介绍了如何定义回调,以便获取正确的i值。(我冒昧地采用了您的GeocodingResult函数并内联了它。

演示

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.