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's a modern solution using a promise:
function getAddress (latitude, longitude) {
return new Promise(function (resolve, reject) {
var request = new XMLHttpRequest();
var method = 'GET';
var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&sensor=true';
var async = true;
request.open(method, url, async);
request.onreadystatechange = function () {
if (request.readyState == 4) {
if (request.status == 200) {
var data = JSON.parse(request.responseText);
var address = data.results[0];
resolve(address);
}
else {
reject(request.status);
}
}
};
request.send();
});
};
And call it like this:
getAddress(lat, lon).then(console.log).catch(console.error);
The promise returns the address object in 'then' or the error status code in 'catch'