2011-04-07 113 views
43

我只需要一些簡單的示例代碼,它可以告訴我如何從輸入的郵政編碼或城市/州獲取一個latlng元素。從郵政編碼獲取LatLng - Google Maps API

+0

是否有特定的語言你尋找你的例子是在? – Mark 2011-04-07 18:57:17

+1

Javascript hopefully ... – Scott 2011-04-07 19:00:49

回答

72

不能你只需要調用下面進行更換操作{}郵政編碼與郵遞區號或城市和州 http://maps.googleapis.com/maps/api/geocode/json?address= {}郵政編碼

Google Geocoding

這是一個帶鏈接如何使用JavaScript地理編碼:Geocode walk-thru。如果您需要特定的緯度/經度號碼的通話geometry.location.lat()或geometry.location.lng()(API for google.maps.LatLng class

例子來獲得緯度/經度:

var lat = ''; 
    var lng = ''; 
    var address = {zipcode} or {city and state}; 
    geocoder.geocode({ 'address': address}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
     lat = results[0].geometry.location.lat(); 
     lng = results[0].geometry.location.lng(); 
     }); 
     } else { 
     alert("Geocode was not successful for the following reason: " + status); 
     } 
    }); 
    alert('Latitude: ' + lat + ' Logitude: ' + lng); 
+2

我不小心在另一個線程中發佈了相同的答案,那麼它不會讓我發佈另一個3分鐘!哈哈 這將允許您用一個地址做: http://maps.googleapis.com/maps/api/geocode/xml?address=Mountain+View,+CA&sensor=false 返回將有 37.3860517 -122.0838511 在步行線頭 – Tony 2011-04-07 18:53:44

+0

,如果我個子帶拉鍊的地址,這項工作也woudl? – Scott 2011-04-07 19:09:44

+0

是的,這裏有一個可以測試的例子。文本框位於左上角。 http://code.google.com/apis/maps/documentation/javascript/examples/geocoding-simple.html – Mark 2011-04-07 19:12:11

6

只是一個提示: 郵政編碼不是全球唯一的所以這是值得提供國家ISO代碼在請求(https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)。

e.g尋找拋光(ISO代碼PL)郵政編碼01-210的座標:

https://maps.googleapis.com/maps/api/geocode/json?address=01210,PL

如何獲取用戶的國家代碼?

如果您想基於IP地址有它的服務,例如,你可以做得到的要求,讓您的用戶國家簡介: http://ip-api.com/json

+0

感謝您的提示,只是使用地址= 01210沒有提供正確的結果。與「,PL」加法它工作正常! – Havrin 2017-10-30 14:52:55

相關問題