0
這與此問題類似:HERE。但我仍然無法解決這個問題。 我想從我的地理編碼器獲取緯度/經度值,但我無法在if語句之外訪問它們。我知道大多數情況都在工作,因爲我可以通過console.log()
訪問geocode lat/lng值,但我無法將它們取出。我認爲這與js範圍有關。如果我使用下面的代碼,我得到這個錯誤:如何訪問外部for循環的地理編碼座標?
"Uncaught TypeError: Cannot read property 'geocode' of undefined".
但如果我註釋掉這部分var myLoc = codeAddress(addressInput);
我可以console.log()
獲取數組。
如何獲取loc(或每個值)數組?
這是我的代碼。
var geocoder;
var map;
var addressInput = '<?php
echo $_GET["q"]; ? > ';
var loc = [];
function initialize() {
geocoder = new google.maps.Geocoder();
codeAddress(addressInput);
}
function codeAddress(address) {
// next line creates asynchronous request
geocoder.geocode({
'address': address
}, function(results, status) {
// and this is function which processes response
if (status == google.maps.GeocoderStatus.OK) {
loc[0] = results[0].geometry.location.lat();
loc[1] = results[0].geometry.location.lng();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
console.log(loc);
// above shows the correct lat/lng values in the console when I comment out the 'myLoc' code below.
});
return loc;
}
var myLoc = codeAddress(addressInput);
google.maps.event.addDomListener(window, 'load', initialize);
地址解析器是異步的,你不能從它的回調函數返回任何東西,你在那裏時,可這裏的/它來使用它。你需要什麼來使用座標? – geocodezip
我有一個搜索功能,有人輸入一個地址,然後我把這個地址改爲lat/lng(帶地理編碼功能)。然後我想根據商店數據庫(使用lat/lng座標)檢查這些座標,並在另一個頁面的列表中獲取最接近的匹配座標/商店。基本上我需要從這個地理編碼發送座標到另一個頁面。 –
你最近怎麼樣?我在發佈的代碼中看不到任何內容。 – geocodezip