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); 
+0

地址解析器是異步的,你不能從它的回調函數返回任何東西,你在那裏時,可這裏的/它來使用它。你需要什麼來使用座標? – geocodezip

+0

我有一個搜索功能,有人輸入一個地址,然後我把這個地址改爲lat/lng(帶地理編碼功能)。然後我想根據商店數據庫(使用lat/lng座標)檢查這些座標,並在另一個頁面的列表中獲取最接近的匹配座標/商店。基本上我需要從這個地理編碼發送座標到另一個頁面。 –

+0

你最近怎麼樣?我在發佈的代碼中看不到任何內容。 – geocodezip

回答

1

的問題是,獲取代碼執行的第一行,除了從您指定的全局變量maploc等,是:

var myLoc = codeAddress(addressInput); 

而在這一點上geocoder這尚未創建codeAddress功能需求。

鑑於您幾乎立即在窗口加載後再次調用codeAddress,我不確定此初始調用的重點。只要改變你的代碼:

var geocoder, map, myLoc; 

var addressInput = '<?php 
    echo $_GET["q"]; ? > '; 
var loc = []; 

function initialize() { 
    geocoder = new google.maps.Geocoder(); 
    myLoc = codeAddress(addressInput); 
    console.log(myLoc); 
} 

function codeAddress(address) { 
    geocoder.geocode({ 
     'address': address 
    }, function(results, status) { 
     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); 
    }); 
    return loc; 
} 

google.maps.event.addDomListener(window, 'load', initialize);