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!
Related
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!");
}
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);
}
});
I'm trying to get a geolocation and turn that into text. I got code to do that but it gives me an error. How can this error be solved?
The error: TypeError: 'undefined' is not an object (evaluating 'geocoder.geocode')
The code:
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'location':latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
alert(results[0].formatted_address)
//find country name
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city= results[0].address_components[i];
break;
}
}
}
//city data
alert(city.short_name + " " + city.long_name)
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
To Reverse Geocode, the request structure contains latLng, not location
From the example in the documentation slightly modified (not tested):
function codeLatLng(lat, lng) {
// remove irrelevant code
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
Also, this is not correct, if you are going to use the first result (result[0]), you should check whether that existst (if results[0] ... not if results[1]):
if (results[1]) {
//formatted address
alert(results[0].formatted_address)
Looking at your jsfiddle, you are not loading the API correctly. Please see the documentation on the correct way(s) to load the API
I have a JavaScript postcode search that searches for the 3 closet stores in the UK depending on what is entered into the input. At the moment it finds the 3 stores fine.
Firstly, I want to drop a marker at the postcode entered in the input.
Secondly, when the three results show up, they are marked on the map. I want to have a link called directions that, once clicked, will show directions from the start to the chosen store.
I have tried the following code but it doesn't work...however it does get the postcode data from the input and from the directions link and shows them in the console. Will I need to convert them into long and lat for it to work?
function calcRoute() {
var start = document.getElementById('address').value;
var end = document.getElementById('get-directions').name;
//console.log(start, end)
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
I have this code for my start marker, but this doesn't seem to work either
function initialize() {
var start_marker = new google.maps.LatLng(document.getElementById('address').value);
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: start_marker
}
marker = new google.maps.Marker({
map:map,
draggable:false,
animation: google.maps.Animation.DROP,
position: start_marker,
});
map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsDisplay.setMap(map);
}
This part gets the long/lat data from the postcode,
this.geocode = function(address, callbackFunction) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var result = {};
result.latitude = results[0].geometry.location.lat();
result.longitude = results[0].geometry.location.lng();
callbackFunction(result);
//console.log(result);
//console.log("Geocoding " + geometry.location + " OK");
addMarker(map, results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " + status);
callbackFunction(null);
}
});
And the function for the addMarker is here:
function addMarker(map, location) {
console.log("Setting marker for (location: " + location + ")");
marker = new google.maps.Marker({
map : map,
animation: google.maps.Animation.DROP,
position : location
});
}
Any help would be greatly appreciated!
The constructor for a google.maps.LatLng requires two floating point numbers as arguments, not a string:
var start_marker = new google.maps.LatLng(document.getElementById('address').value);
If all you have is an address, you need to use the Geocoding service to retrieve coordinates for that address if you want to display a marker on the map.
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