Sometimes, we want to get city name using geolocation with JavaScript.
In this article, we’ll look at how to get city name using geolocation with JavaScript.
How to get city name using geolocation with JavaScript?
To get city name using geolocation with JavaScript, we can use the geolocator.js library.
To install it, we add
<script type="text/javascript" src="geolocator.min.js"></script>
into our HTML code.
Then we write
const options = {
enableHighAccuracy: true,
fallbackToIP: true,
addressLookup: true,
};
geolocator.locate(options, (err, location) => {
console.log(location.address.city);
});
to call geolocator.locate
with the options
object to set some options.
We set fallbackToIP
to true
to fallback to using IP address for getting location if geolocation isn’t available.
And we set addressLookup
to true
to get the address data from the location.
Then we get the city name with location.address.city
in the callback.
Conclusion
To get city name using geolocation with JavaScript, we can use the geolocator.js library.