Google map API - Search by Postcode - javascript

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

Related

How to reverse geocode with maps?

I am using leaflet to display markers on a map, when I click on a marker, I get its lat and lng, then I am sending these to google maps geocoder to retrieve the address name:
var markerCoords = [];
circle.on('click', function (e) {
var curPos = e.target.getLatLng();
markerCoords.push(curPos.lng);
markerCoords.push(curPos.lat);
geocodeLatLng();
});
var geocoder = new google.maps.Geocoder;
function geocodeLatLng(geocoder) {
var latlng = {lat: parseFloat(markerCoords[1]), lng: parseFloat(markerCoords[0])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
console.log(results[0].formatted_address);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
But it gives me:
Cannot read property 'geocode' of undefined
NOTE
This line is fine
var latlng = {lat: parseFloat(markerCoords[1]), lng: parseFloat(markerCoords[0])};
As if I do console.log I get the correct lat and lng
You have a typo in your code. You aren't passing the reference to the geocoder into the geocodeLatLng function, so it is null inside the function:
var markerCoords = [];
circle.on('click', function (e) {
var curPos = e.target.getLatLng();
markerCoords.push(curPos.lng);
markerCoords.push(curPos.lat);
geocodeLatLng(geocoder); // <============================================== **here**
});
var geocoder = new google.maps.Geocoder;
function geocodeLatLng(geocoder) {
var latlng = {lat: parseFloat(markerCoords[1]), lng: parseFloat(markerCoords[0])};
geocoder.geocode({'location': latlng}, function(results, status) {
// ... code to process the result
});
}
This is probably because google api hasn't loaded yet, you can try loading it before other scripts, to make sure, check console.log("google api object is", geocoder) and check Geocode to verify whether google has loaded before calling the api.
Edit : you don't need geocoder as parameter in geocodeLatLng function,as pointed out by #geocodezip, it will be undefined if you don't pass it. Since parameter will get priority over outer scope when variable names are same.
Following procedure will give you the address of user's current position, you can pass any lat, lng and get its address:-
//getting location address from latitude and longitude with google api
navigator.geolocation.getCurrentPosition(success, error);
function success(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var geocoder = new google.maps.Geocoder;
console.log("google api object is", geocoder)
var latlng = { lat: lat, lng: long };
geocoder.geocode({ 'location': latlng }, function (results, status) {
if (status === 'OK') {
if (results[0]) {
console.log(results[0].formatted_address);// this will be actual full address
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
function error(err) {
alert("Allow location services!");
}

REQUEST_DENIED for google geocoding API

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();
document.getElementById('latitude').setAttribute('value', latitude);
document.getElementById('longitude').setAttribute('value', longitude);
var lat = parseFloat(latitude);
var lng = parseFloat(longitude);
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
document.getElementById('physicaladdress').setAttribute('value', results[1].formatted_address);
}
}
});
} else {
console.log(""+status);
}
});
This is my javascript file where i am trying to get latitude and longitude from zip code ,it is working fine in localhost but not when it is hosted live(say aws)
{} ,this i am giving into the app.blade.php , any help would be much appreciated sorry if i am missing anything while asking question.

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!

Reverse Geocode on Client Side (Google Maps V3 API)

How do you do a Reverse Geocode on the clientside using Google Maps V3 API? The forward geocode from address to LatLng is straight forward (code below), but how do you do the same for reverse geocode?
Normal Geocode Code:
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
The process is exactly the same, with the minor difference that instead of supplying an address object to the geocode function you supply a LatLng object
Reverse Geocode Code:
var input = document.getElementById("latlng").value;
var latlngStr = input.split(",",2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(11);
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
Example directly from Google
Hope that helps.

Get LatLng from Zip Code - Google Maps API

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

Categories

Resources