2012-06-21 49 views
16

我想知道是否有一种方法可以使用邮政编码代替Lat和Lng,使用此代码段或使用地理编码请求。如何在谷歌地图中使用邮政编码代替Lat和Lng API

<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> 

回答

25

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

API请求的URL应该是这样的,如果你想直接做,或者通过一些其他媒体

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

50323哪里是你的邮政编码。

或者你可以使用谷歌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); 
     } 
    }); 
    } 
+0

感谢您的工作示例。 –

+1

给出错误未捕获的nf:在财产地址中:不是字符串 –

+2

同样的问题在这里,如果我将邮递区号作为字符串传递给南非(尝试8790,来自比利时的邮政编码),并且如果我将邮政编码作为整数传递返回与@ Mohd.Umar所说的相同的错误 – AlvaroAV

相关问题