繁体   English   中英

Google Maps-从未定义的函数返回getPosition

[英]Google maps - returning getPosition from function undefined

我有一个初始化我的Google地图的函数,在该函数中,它调用了另一个与Geocoder一起使用的函数,用于设置一些标记。 我在第二个功能中创建了标记。

为什么在第二个函数中我可以发出alert(marker.getPosition())并获取latlng值。 但是,如果我确实返回marker.getPosition(),然后警告该函数的返回值,则显示为未定义?

示例代码:

function initMap() {
    //Defined Map/Geocoder
    //Defined Array of addresses
    for (var i = 0; i < address.length; i++) {
        alert(geocodeAddress(address[i], geocoder, map)); //Alert shows undefined
    }
}
function geocodeAddress(address, geocoder, resultsMap) {
    geocoder.geocode({'address': address}, function(results, status) {
      if (status === google.maps.GeocoderStatus.OK) {
        var marker = new google.maps.Marker({
          map: resultsMap,
          position: results[0].geometry.location
        });
        alert(maker.getPosition()); //Displays latlng data
        return marker.getPosition();
      }
    });
}

您只是从匿名回调中返回。 您无需将其分配给变量或其他任何对象,并且geocodeAddress函数不会将任何内容返回给initMap函数。 尝试:

function geocodeAddress(address, geocoder, resultsMap) {
    return geocoder.geocode({'address': address}, function(results, status) {
      if (status === google.maps.GeocoderStatus.OK) {
        var marker = new google.maps.Marker({
          map: resultsMap,
          position: results[0].geometry.location
        });

        return marker.getPosition();
      }
    });
}

如果您未成功获得地址解析器的响应,则还需要处理这种情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM