2012-02-27 17 views
3

我編譯使用這種代碼搜索地址的web應用程序中提取緯度和經度:如何從谷歌地圖自動完成

http://code.google.com/intl/en/apis/maps/documentation/javascript/examples/places-autocomplete.html

類型有,紐約,NY。

因此,當用戶使用自動填充選項後,地圖加載到DOM中時,用戶可以將位置地址保存在數據庫中,並且它將以「紐約州紐約州」的形式提供。但是,對於應用程序,我還需要保存經度和緯度。

但我沒有ideia如何從Google API抓取它們。

作爲一個測試應用程序,我仍然使用谷歌代碼。 我想我應該創建一些隱藏字段,併爲用戶選擇地址時分配經度和緯度。

我的問題的任何實施是值得歡迎的!

在此先感謝

P.S: 正如我在StackOverflow的是新我便無法回答自己。 所以我編輯後,通過計算器的建議,這裏是總部設在丹尼爾的回答解決方案,並在谷歌阿比一些研究:

function getLatLng(address) 
{ 
    var geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 'address' : address }, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      var mapLatLng = document.getElementById('mapLatLng'); // mapLatLng is my hidden field, use your own 
      mapLatLng.value = results[0].geometry.location.lat() + ', ' + results[0].geometry.location.lng(); 
     } else { 
      alert("Geocode was not successful for the following reason: " + status); 
     } 

    });    
} 

回答

6

您可以使用谷歌API來獲取經度和您的地址的緯度。正如你已經說過的,你應該實現一個隱藏的字段,結果應該被插入。 然後您可以將位置與座標一起保存。

我最近在我的一個項目實現了這個功能:

function getLatLngFromAddress(city, country){ 

    var address = city +", "+ country; 
    var geocoder = new google.maps.Geocoder(); 

    geocoder.geocode({ 'address': address}, function(results, status) { 

    if (status == google.maps.GeocoderStatus.OK) { 
     $('#latitude').val(results[0].geometry.location.lat()); 
     $('#longitude').val(results[0].geometry.location.lng()); 

    } else { 
     console.log("Geocode was not successful for the following reason: " + status); 
    } 
    }); 
} 
+0

我試過你的代碼實現它,但沒有succ ESS! – 2012-02-27 22:47:05

10

丹尼爾是正確的大部分,在那裏他是不正確的是他的財產訪問這裏:

$('#latitude').val(results[0].geometry.location.Pa) 
$('#longitude').val(results[0].geometry.location.Qa) 

你應該使用提供的lat()和lng()函數:

$('#latitude').val(results[0].geometry.location.lat()) 
$('#longitude').val(results[0].geometry.location.lng()) 
相關問題