谷歌地图从邮政编码中获取纬度和经度

时间:2011-05-23 16:41:18

标签: google-maps

使用google api传递邮政编码是否有可能获得经度和纬度?

感谢任何提示,再见

2 个答案:

答案 0 :(得分: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()
});

答案 1 :(得分:14)

您可以交替使用它:

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

只需在jquery-ajax中调用此url,结果就会得到lat。

使用jquery-ajax的示例

$(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);
       }

    });
});

来自google api的示例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"
}

干杯..