Categories
JavaScript Answers

How to get city name using geolocation with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *