Is there a way to get a city name from a latitude and longitude point using the google maps api for javascript?
If so could I please see an example?
Here is the latest sample of Google's geocode Web Service
https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY
Simply change the YOUR_API_KEY
to the API key you get from Google Geocoding API
P/S: Geocoding API is under Places NOT Maps ;)
Same as @Sanchit Gupta.
in this part
if (results[0]) {
var add= results[0].formatted_address ;
var value=add.split(",");
count=value.length;
country=value[count-1];
state=value[count-2];
city=value[count-3];
x.innerHTML = "city name is: " + city;
}
just console the results array
if (results[0]) {
console.log(results[0]);
// choose from console whatever you need.
var city = results[0].address_components[3].short_name;
x.innerHTML = "city name is: " + city;
}
Following Code Works Fine to Get City Name (Using Google Map Geo API) :
HTML
<p><button onclick="getLocation()">Get My Location</button></p>
<p id="demo"></p>
<script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY"></script>
SCRIPT
var x=document.getElementById("demo");
function getLocation(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition,showError);
}
else{
x.innerHTML="Geolocation is not supported by this browser.";
}
}
function showPosition(position){
lat=position.coords.latitude;
lon=position.coords.longitude;
displayLocation(lat,lon);
}
function showError(error){
switch(error.code){
case error.PERMISSION_DENIED:
x.innerHTML="User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML="Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML="The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML="An unknown error occurred."
break;
}
}
function displayLocation(latitude,longitude){
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);
geocoder.geocode(
{'latLng': latlng},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add= results[0].formatted_address ;
var value=add.split(",");
count=value.length;
country=value[count-1];
state=value[count-2];
city=value[count-3];
x.innerHTML = "city name is: " + city;
}
else {
x.innerHTML = "address not found";
}
}
else {
x.innerHTML = "Geocoder failed due to: " + status;
}
}
);
}
BigDataCloud also has a nice API for this, also for nodejs users.
they have API for client - free. But also for backend, using API_KEY (free according to quota).
Their GitHub page.
the code looks like:
const client = require('@bigdatacloudapi/client')(API_KEY);
async foo() {
...
const location: string = await client.getReverseGeocode({
latitude:'32.101786566878445',
longitude: '34.858965073072056'
});
}
In case if you don't want to use google geocoding API than you can refer to few other Free APIs for the development purpose. for example i used [mapquest] API in order to get the location name.
you can fetch location name easily by implementing this following function
const fetchLocationName = async (lat,lng) => {
await fetch(
'https://www.mapquestapi.com/geocoding/v1/reverse?key=API-Key&location='+lat+'%2C'+lng+'&outFormat=json&thumbMaps=false',
)
.then((response) => response.json())
.then((responseJson) => {
console.log(
'ADDRESS GEOCODE is BACK!! => ' + JSON.stringify(responseJson),
);
});
};
This is called Reverse Geocoding
Documentation from Google:
http://code.google.com/apis/maps/documentation/geocoding/#ReverseGeocoding.
Sample Call to Google's geocode Web Service:
http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true&key=YOUR_KEY