谷歌地图多个标记

Google Maps multiple markers

本文关键字:谷歌地图      更新时间:2023-09-26

我有一个小问题,我有以下代码,显然除了标记的标题外,一切正常。它始终显示数组列表的最后一个标题。有人知道为什么会出现此错误吗?

法典:

$(document).ready(function() {
            var options = {
                zoom: 7,
                center: new google.maps.LatLng(42.19708, 2.19075),
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                mapTypeControl: true
            };
            var geocoder = new google.maps.Geocoder();
            var map = new google.maps.Map(document.getElementById('map_canvas'), options);
            var companys = [
                ['Giga S.L', 'Plaça de Catalunya, Barcelona'],
                ['Torre M', 'Plaça d''Espanya, Barcelona']
            ];
            var address;
            var title;
            for (var i = 0; i < companys.length; i++) {
                address = companys[i][1];
                title = companys[i][0];
                geocoder.geocode({'address': address}, function(results, status) {
                    if (status === google.maps.GeocoderStatus.OK) {
                        map.setCenter(results[0].geometry.location);
                        new google.maps.Marker({
                            map: map,
                            animation: google.maps.Animation.DROP,
                            position: results[0].geometry.location,
                            title: title // ERROR: ALWAYS THE SAME TITLE
                        });
                    } else {
                        alert('Geocode was not successful for the following reason: ' + status);
                    }
                });
            }
        });

提前谢谢你。

此致敬意。

解决此问题的一种方法是将对geocode的调用包装在立即调用的函数表达式 (IFFE) 中,并将变量作为参数传递:

(function(address, title) { // the variables are passed in here as function parameters
  geocoder.geocode({'address': address}, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      new google.maps.Marker({
        map: map,
        animation: google.maps.Animation.DROP,
        position: results[0].geometry.location,
        title: title
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}(address, title)); // pass in address/title into the IFFE

geocoder.geocode有一个回调函数。这意味着代码以异步方式运行。您必须重构代码才能从回调中检索公司标题。

在您的代码中,for 循环在geocode回调返回之前已经完成,这就是变量标题设置为最后一个的原因。