2013-04-08 174 views
0

我需要使用下面的代碼一個城市的經緯度值...但我得到的結果作爲「經緯度值不確定」我的代碼是如何在google maps api中使用geocoder獲取城市的latlng值?

geocoder.geocode({'address': acity}, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       latlng1 = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()); 
       } 
     }); 

更新:如果我單獨顯示緯度和經度值它被顯示,如果使它們被分配到latlng1「latlng1未定義」,它將顯示

+0

'results [0] .geometry.location.lat()'包含什麼? – ASGM 2013-04-08 10:11:47

+1

我希望它會包含我發送的acity參數的緯度... – Ree 2013-04-08 10:13:44

+0

對,但你能檢查它實際上包含了什麼嗎?無論它(和相應的lng())是否包含有效值都可以幫助您找到問題。 – ASGM 2013-04-08 10:19:30

回答

0

根據文檔,位置作爲LatLng對象返回。您不需要創建新的LatLng對象。

幾何包含以下信息:

位置包含地址解析緯度,經度值。請注意,我們 將此位置作爲LatLng對象返回,而不是格式化的字符串。

例子:

geocoder.geocode({ 'address': address}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
     window.test = results[0].geometry.location 
     setTimeout(function() { 
      console.log(window.test.lat()); 
      console.log(window.test.lng()); 
     }, 5000) 
     } 
    }); 

編輯:我想我誤會了,我覺得你只是想在全球範圍內的經緯度對象。我編輯了這個例子。

0

如果我理解你的權利,你試圖做這樣的事情:

var latlng1; 

geocoder.geocode({ 
    'address': acity 
}, function(results, status) { 
    if(status == google.maps.GeocoderStatus.OK) { 
     latlng1 = new google.maps.LatLng(
      results[0].geometry.location.lat(), 
      results[0].geometry.location.lng() 
     ); 
    } 
}); 

// Now do stuff with latlng1 here 

這不會有任何效果,而且也沒有辦法可以使它發揮作用。正如您發現的那樣,在「」收到結果之前,「現在執行latlng1」代碼運行

地理編碼器API與任何訪問數據服務器的JavaScript API都是異步的。 API調用立即返回,並在數據準備就緒時調用回調函數。

所以你需要做的是通話自己的一種功能,當數據準備好,像這樣的(也簡化,以去除多餘的LatLng構造函數調用):

geocoder.geocode({ 
    'address': acity 
}, function(results, status) { 
    if(status == google.maps.GeocoderStatus.OK) { 
     doStuffWithLatLng(results[0].geometry.location); 
    } 
}); 

function doStuffWithLatLng(latlng) { 
    // Now do stuff with latlng1 here 
} 

當然還是你可以將「do stuff」代碼放在geocoder回調中:

geocoder.geocode({ 
    'address': acity 
}, function(results, status) { 
    if(status == google.maps.GeocoderStatus.OK) { 
     var latlng1 = results[0].geometry.location; 
     // Now do stuff with latlng1 here 
    } 
}); 
+0

我需要訪問整個函數latlng1 ...我試過你第一個例子傳遞給一個單獨的功能...但它沒有工作...仍然僅對latlng1顯示未定義的值....它不可能在IF語句中使用第二個例子,因爲我需要在整個函數中訪問latlng1值 – Ree 2013-04-09 04:34:13

+0

問題是,當* latlng1'數據可用時,您必須擔心*,而不僅僅是* where *在你的代碼中它是可用的。你當然可以將這個值存儲在一個全局變量或類似的東西中,但是這並不能幫助你知道*何時該變量可以使用。 geocoder.geocode()函數在數據準備好之前立即返回。直到你的回調函數被調用,數據才準備好。任何使用這些數據的代碼都應該在您可以調用的函數中,否則數據將無法準備好。 – 2013-04-09 14:56:14

相關問題