How to use zip code instead Lat and Lng in Google maps API

前端 未结 1 1707
情书的邮戳
情书的邮戳 2020-12-29 05:37

I wonder if there is a way to use zipcode instead of Lat and Lng, using this snippet or using Geocoding Requests.

           


        
相关标签:
1条回答
  • 2020-12-29 06:29

    You can use the Google GeoCode API to request the latitude and longitude for the zipcode and go from there.

    The API Request URL would look like this if you wanted to do this directly or via some other medium

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

    Where 50323 is your zip code.

    Or you could use the google Javascript API to do this all via 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 讨论(0)
提交回复
热议问题