Get LatLng from Zip Code - Google Maps API - javascript

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.

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];
}

While working on my internship project I found a website for this https://thezipcodes.com/
Create a free account and get the API key from account Section.
https://thezipcodes.com/api/v1/search?zipCode={zipCode}&countryCode={2digitCountryCode}&apiKey={apiKey}
I found majority of data here.

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];
}

<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY"></script>
<script>
var latitude = '';
var longitude = '';
var geocoder = new google.maps.Geocoder();
geocoder.geocode(
{
componentRestrictions: {
country: 'IN',
postalCode: '744102'
}
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
console.log(latitude + ", " + longitude);
} else {
alert("Request failed.")
}
});
</script>
https://developers.google.com/maps/documentation/javascript/geocoding#ComponentFiltering

Related

Google map API - Search by Postcode

I am using Google Map Javascript API and it is working fine.
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == 'OK') {
map.setCenter(results[0].geometry.location);
The only issue is I cannot search by only Postcode. For example in Australia if I only search by 2000 (address = 2000) which is Sydney postcode, it doesn't return any results but if I go to the Google map page and type 2000, it shows the correct area.
I was wondering if there is any way to search by Postcode.
Have you tried restricting the country first?
Try this and let me know:
function codeAddress () {
var lat = '';
var lng = '';
var address = document.getElementById("cp").value;
geocoder.geocode( {
'address': address,
componentRestrictions: {
country: 'PT'
}
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
//Just to keep it stored
positionArray.push(new google.maps.LatLng(lat,lng));
//Make the marker
new google.maps.Marker({
position:new google.maps.LatLng(lat,lng),
map:map
});
}else {
alert("Geocode was not successful for the following reason: " + status);
}
});

Google maps API Searching postcodes in a specific country

I'm trying to set a Post Code in order to get Lat and Long Coordinates and place a marker on it. Until now, everything is fine.
The problem comes when I give a postcode input and it ends up making a marker somewhere in another part of the world.
Ex: I type 2975-435 and I get :
https://maps.googleapis.com/maps/api/geocode/json?address=2975-435&key=YOURKEY
"formatted_address" : "Balbey Mahallesi, 435. Sk., 07040 Muratpaşa/Antalya, Turquia",
And I want to make this postcode only be searched in Portugal.
https://maps.googleapis.com/maps/api/geocode/json?address=2975-435+PT
This way I get:
"formatted_address" : "2975 Q.ta do Conde, Portugal",
Exactly what I wanted.
The problem is, how do I make this in JS code?
Here is the code I have till now
function codeAddress () {
var lat = '';
var lng = '';
var address = document.getElementById("cp").value;
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();
//Just to keep it stored
positionArray.push(new google.maps.LatLng(lat,lng));
//Make the marker
new google.maps.Marker({
position:new google.maps.LatLng(lat,lng),
map:map
});
}else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Thank you
To restrict a result to certain country you can apply a component filtering:
https://developers.google.com/maps/documentation/javascript/geocoding#ComponentFiltering
So, your JavaScript code will be
function codeAddress () {
var lat = '';
var lng = '';
var address = document.getElementById("cp").value;
geocoder.geocode( {
'address': address,
componentRestrictions: {
country: 'PT'
}
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
//Just to keep it stored
positionArray.push(new google.maps.LatLng(lat,lng));
//Make the marker
new google.maps.Marker({
position:new google.maps.LatLng(lat,lng),
map:map
});
}else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
You can see a component filtering in action using the Geocoder tool:
https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/utils/geocoder/#q%3D2975-435%26options%3Dtrue%26in_country%3DPT%26nfw%3D1
Hope it helps!

How can I get the value of these variables?

Im trying to get the value of the variables "latitude" and "longitude".
var latitude;
var longitude;
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("txtAddress").value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
alert("Latitude: " + latitude + "\nLongitude: " + longitude);
} else {
alert("Request failed.")
}
});
How can I do it?
I don't think you can. It's an async call.
The way I handled something similar was to call your next function right after latitude and longitude are set.
For example:
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
myNextFunction(latitude, longitude);

returning variable from javascript function

I'm trying to return longitude and latitude from this function, I can console.log both of them, but when I try to return one of them, I get undefined.
How can I return latitude, longitude?
function latLong(location) {
var geocoder = new google.maps.Geocoder();
var address = location;
var longitude;
var latitude;
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
console.log(longitude);
});
}
The geocoder is asynchronous, and you can't return data from an asynchronous function, you could however use a callback
function latLong(location, callback) {
var geocoder = new google.maps.Geocoder();
var address = location;
var longitude;
var latitude;
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
callback(latitude, longitude);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
and to use it do
latLong(location, function(lat, lon) {
// inside this callback you can use lat and lon
});
You don't.
The generally used technique is to pass a callback to latLong function as a parameter, and run this function when you receive the result.
Something like:
function latLong(location, callback) {
var geocoder = new google.maps.Geocoder();
var address = location;
var longitude;
var latitude;
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
callback(latitude, longitude);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
console.log(longitude);
});
}

Why is this variable undefined or not returned?

I have the following code:
/*
* converts a string to geolocation and returns it
*/
function stringToLatLng(string){
if(typeof string == "string"){
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': string}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log("LatLng: "+results[0].geometry.location);
return results[0].geometry.location;
} else {
console.log("Geocode was not successful for the following reason: " + status);
}
});
}
}
the LatLng prints the correct location to the console, but when I write this:
var pos = stringToLatLng('New York');
console.log(pos);
I get undefined back. Why is that? thanks
Something like this:
function stringToLatLng(strloc, callback){
if(typeof string == "string"){
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': strloc}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
callback.call({}, results[0].geometry.location);
} else {
console.log("Geocode was not successful for the following reason: " + status);
}
});
}
}
stringToLatLng('New York', function(pos){
console.log(pos);
});
In your code, when you return, you are actually returning from the function(results, status){..} function, not the stringToLatLng function, as said in the comments its an asynchronous call, so you must use a callback.
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
ref:
Javascript geocoding from address to latitude and longitude numbers not working

Categories

Resources