In this post we are going to see an example of finding user location and showing it on leaflet interactive map using javascript/ReactJS. It will ask for browser permission to access user location(coordinates) and use google geocode api to find the location. If browser location permission is denied, it will find the location of your device public ip address.
Demo of this example can be seen here, github code. I have been using the same logic and javascript code for my company website to find the user location and show the content based on different states in Australia.
Folder structure:
This is very simple web application, below is the folder structure of this web app. All the JavaScript code is included in App.js . We are using google geocoding api to find the location address. Its key needs to be saved in env file.
Finding user coordinates:
To show any location on map, we need to have the coordinates of that location ie latitude and longitude. Once we have lat, long, we can use them to find the location address using various APIs.
The W3C Geolocation API is a standard way to retrieve the geographical location information for a client-side device. It allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked for permission to report location information.
Browsers Navigator object has methods and properties about the application running the script. The Geolocation API is accessed via a call to navigator.geolocation; this will cause the user's browser to ask them for permission to access their location data. So either user will allow the location access or block it.
Case 1: Location access allowed via browser
In this case when user allows location access, this web app uses google geocoding api to find the location address using user coordinates.
We can also use other apis like geonames api for this. For geonames api we do not need any secret key (we do require key for google geocode api above)
Case 2: Location access blocked via browser
When user access access is not provided, it will use ipapi.co API to find the device public ip address.
There are many other APIs we can use for finding the public ip location, some of them are as below, information about them can be found here.
1: geoipify.whoisxmlapi.com
2: geo.ipify.org
3: IPInfo.io
4: DB-IP.com
5: IP2Location.com
6: IPData.co
7: IPGeolocation.io
8: IPStack.com
9: ClearIP.io
10: IPWhois.io
Showing location coordinates on map:
We are using Leaflet JavaScript library for interactive maps.
Thank you
Top comments (0)