如何在点击标记和地址时获取latlng必须在infoWindow中显示

时间:2015-07-06 08:22:10

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

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

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并转换为地址并且必须显示到infowindow

2 个答案:

答案 0 :(得分:2)

在你调用setInfoWindow的地方,你传递的是一个在该位置附近带有{ }符号的结构:

setInfoWindow({this.position})

然而,在函数本身中,当你直接引用它时,你就把它视为一个简单的变量:

function setInfoWindow(pos){

然后

 geocoder.geocode({'latLng': pos}

只需将位置传递给函数:

setInfoWindow(this.position)

答案 1 :(得分:0)

这是因为异步而发布的。方法

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

当我点击标记时,我调用了一种方法,其中,我显示了infowindow