簡體   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