如何在Google Maps API中使用邮政编码代替Lat和Lng

时间:2012-06-21 22:33:51

标签: google-maps maps zipcode

我想知道是否有办法使用zipcode代替Lat和Lng,使用此代码段或使用地理编码请求。

    <script type="text/javascript">
        function initialize() {
            var latlng = new google.maps.LatLng(22.1482635,-100.9100755);
            // var latlang = new google.maps.zipcode(7845); <- Is there a way to do that?
            var myOptions = {
                zoom: 8,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            var marker = new google.maps.Marker({
                position: latlng,
                map: map,
                title:"zipcode"
            });

        }
    </script>

1 个答案:

答案 0 :(得分:27)

您可以使用Google GeoCode API来请求邮政编码的纬度和经度,并从那里开始。

如果您想直接或通过其他媒介

执行此操作,API请求网址将如下所示

http://maps.googleapis.com/maps/api/geocode/json?address=50323&sensor=false

50323是您的邮政编码。

或者您可以使用google Javascript API通过jQuery完成此操作。

var geocoder; //To use later
var map; //Your map
function initialize() {
  geocoder = new google.maps.Geocoder();
  //Default setup
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var myOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

//Call this wherever needed to actually handle the display
function codeAddress(zipCode) {
    geocoder.geocode( { 'address': zipCode}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        //Got result, center the map and put it out there
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }