2011-05-23 220 views

回答

27

只需創建的google.maps.Geocoder一個實例,並調用其geocode方法,通過在具備必要的屬性爲它是一個GeocoderRequest的對象。

這樣:

var geocoder = new google.maps.Geocoder(); 
geocoder.geocode({address: /* zip you got from user input */}, 
    function(results_array, status) { 
     // Check status and do whatever you want with what you get back 
     // in the results_array variable if it is OK. 
     // var lat = results_array[0].geometry.location.lat() 
     // var lng = results_array[0].geometry.location.lng() 
}); 
+0

每次都遇到'ZERO RESULTS'我嘗試一個郵政編碼。 – Leeish 2014-07-10 17:06:17

+0

您可以嘗試在請求中添加['region'](https://developers.google.com/maps/documentation/javascript/reference?csw=1#GeocoderRequest)並查看是否有助於Google消除該值的歧義。 – 2014-07-10 17:35:19

11

您可以使用此交替:

URLhttp://maps.googleapis.com/maps/api/geocode/json?address=santa+cruz&components=postal_code:695564&sensor=false

只需撥打這個網址在jQuery的Ajax和你會得到結果Lat Long網。

示例使用jQuery的Ajax:從谷歌API

$(document).ready(function(){ 

    var zipcode = 695564; 

    $.ajax({ 
     url : "http://maps.googleapis.com/maps/api/geocode/json?address=santa+cruz&components=postal_code:"+zipcode+"&sensor=false", 
     method: "POST", 
     success:function(data){ 
      latitude = data.results[0].geometry.location.lat; 
      longitude= data.results[0].geometry.location.lng; 
      alert("Lat = "+latitude+"- Long = "+longitude); 
     } 

    }); 
}); 

樣品JSON結果:

{ 
    "results" : [ 
     { 
     "address_components" : [ 
      { 
       "long_name" : "695564", 
       "short_name" : "695564", 
       "types" : [ "postal_code" ] 
      }, 
      { 
       "long_name" : "Thiruvananthapuram", 
       "short_name" : "TVM", 
       "types" : [ "administrative_area_level_2", "political" ] 
      }, 
      { 
       "long_name" : "Kerala", 
       "short_name" : "KL", 
       "types" : [ "administrative_area_level_1", "political" ] 
      }, 
      { 
       "long_name" : "India", 
       "short_name" : "IN", 
       "types" : [ "country", "political" ] 
      } 
     ], 
     "formatted_address" : "Kerala 695564, India", 
     "geometry" : { 
      "bounds" : { 
       "northeast" : { 
        "lat" : 8.5894172, 
        "lng" : 77.0210912 
       }, 
       "southwest" : { 
        "lat" : 8.5616185, 
        "lng" : 76.96664299999999 
       } 
      }, 
      "location" : { 
       "lat" : 8.5753702, 
       "lng" : 76.99310740000001 
      }, 
      "location_type" : "APPROXIMATE", 
      "viewport" : { 
       "northeast" : { 
        "lat" : 8.5894172, 
        "lng" : 77.0210912 
       }, 
       "southwest" : { 
        "lat" : 8.5616185, 
        "lng" : 76.96664299999999 
       } 
      } 
     }, 
     "partial_match" : true, 
     "types" : [ "postal_code" ] 
     } 
    ], 
    "status" : "OK" 
} 

乾杯..

+1

我試着http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:530016&sensor=false其工作的爐排 – 2016-03-10 14:36:15