Sometimes, we want to get city name from a latitude and longitude point with JavaScript.
In this article, we’ll look at how to get city name from a latitude and longitude point with JavaScript.
How to get city name from a latitude and longitude point with JavaScript?
To get city name from a latitude and longitude point with JavaScript, we can use the node-geocode
library.
To install it, we run
npm i node-geocoder
Then we write
const NodeGeocoder = require("node-geocoder");
const options = {
provider: "google",
httpAdapter: "https",
apiKey: "...",
formatter: "json",
};
const geocoder = NodeGeocoder(options);
geocoder.reverse({ lat: 42.5967439, lon: 77.3285038 }, (err, res) => {
console.log(res);
});
to create the NodeGeocode
object with the options
object.
apiKey
is the API key for for Mapquest, OpenCage, or Google Premier.
formatter
returns the result in 'json'
format.
We can also return it as a 'gpx'
or 'string'
.
Then we call reverse
with the lat
latitude and lon
longitude.
And we get the res
from the callback which has the city included.
Conclusion
To get city name from a latitude and longitude point with JavaScript, we can use the node-geocode
library.