Get LatLng from Zip Code - Google Maps API

2019-01-13 00:31发布

问题:

All I want is some simple example code that shows me how to obtain a latlng element from an inputted zip code OR a city/state.

回答1:

Couldn't you just call the following replaceing the {zipcode} with the zip code or city and state http://maps.googleapis.com/maps/api/geocode/json?address={zipcode}

Google Geocoding

Here is a link with a How To Geocode using JavaScript: Geocode walk-thru. If you need the specific lat/lng numbers call geometry.location.lat() or geometry.location.lng() (API for google.maps.LatLng class)

EXAMPLE to get lat/lng:

    var lat = '';
    var lng = '';
    var address = {zipcode} or {city and state};
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
         lat = results[0].geometry.location.lat();
         lng = results[0].geometry.location.lng();
        });
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
    alert('Latitude: ' + lat + ' Logitude: ' + lng);


回答2:

Just a hint: zip codes are not worldwide unique so this is worth to provide country ISO code in the request (https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2).

e.g looking for coordinates of polish (iso code PL) zipcode 01-210:

https://maps.googleapis.com/maps/api/geocode/json?address=01210,PL

how to obtain user country code?

if you would like to get your user country info based on IP address there are services for it, e.g you can do GET request on: http://ip-api.com/json



回答3:

Here is the function I am using for my work

function getLatLngByZipcode(zipcode) 
{
    var geocoder = new google.maps.Geocoder();
    var address = zipcode;
    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var latitude = results[0].geometry.location.lat();
            var longitude = results[0].geometry.location.lng();
            alert("Latitude: " + latitude + "\nLongitude: " + longitude);
        } else {
            alert("Request failed.")
        }
    });
    return [latitude, longitude];
}