【问题标题】:How to get latlng on click on marker and address have to be shown in infoWindow如何在点击标记和地址时获得 latlng 必须显示在 infoWindow
【发布时间】:2015-07-06 08:22:10
【问题描述】:

我的谷歌地图 API 中有几个标记

marker = new google.maps.Marker({
                    position: pos,
                    map: map
                });
                var infoWindow = new google.maps.InfoWindow();   
                google.maps.event.addListener(marker, 'click', (function(marker, i) {
                    return function() {
                        infoWindow.setContent(setInfoWindow({this.position}));
                        infoWindow.open(map, marker);
                    }
                })(marker, i));

在这里,当我点击标记时,我显示了 infowindow,同时,我在 infowindow 上分配了从 latlng 转换为地址的地址

这是 setInfoWindow();

function setInfoWindow(pos){
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'latLng': pos}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            console.log(results.formatted_address);
                return results.formatted_address;
        } else {
          alert('Geocoder failed due to: ' + status);
        }
    });
}

这里显示未定义。

我对这个程序是否正确?

我的简单想法是

当我点击标记时,我必须从标记中获取 latlng 并转换为地址,并且必须显示到信息窗口中

【问题讨论】:

标签: javascript google-maps google-maps-api-3


【解决方案1】:

在您调用 setInfoWindow 的地方,您传递的是一个带有 { } 符号的结构:

setInfoWindow({this.position})

但是在函数本身中,当您直接引用它时,您将它视为一个简单的变量:

function setInfoWindow(pos){

然后

 geocoder.geocode({'latLng': pos}

只需将位置本身传递给函数:

setInfoWindow(this.position)

【讨论】:

    【解决方案2】:

    这是由于异步而发出的。方法。

    google.maps.event.addListener(marker, 'click', (function(marker, i) {
                        return function() {
                            setInfoWindow(this.position);
                            infoWindow.open(map, marker);
                        }
                    })(marker, i));
    
    
    function setInfoWindow(pos){
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({'latLng': pos}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                    infoWindow.setContent(results[0].formatted_address);
            } else {
              alert('Geocoder failed due to: ' + status);
            }
        });
    }
    

    当我点击标记时,我调用了一个方法,在那个方法中,我显示了信息窗口

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-22
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 2016-02-22
      相关资源
      最近更新 更多