Get LatLng from Zip Code - Google Maps API
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);
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
Here is the most reliable way to get the lat/long from zip code (i.e. postal code):
https://maps.googleapis.com/maps/api/geocode/json?key=YOUR_API_KEY&components=postal_code:97403
This is just an improvement to the previous answers because it didn't work for me with some zipcodes even when in https://www.google.com/maps it does, I fixed just adding the word "zipcode " before to put the zipcode, like this:
function getLatLngByZipcode(zipcode)
{
var geocoder = new google.maps.Geocoder();
var address = zipcode;
geocoder.geocode({ 'address': 'zipcode '+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];
}