GET USER’S CURRENT LOCATION USING JAVASCRIPT
With the help of this tutorial, you can retrieve the user’s current position using the Geolocation Web API.
The Javascript Geolocation API provides a great and standard way to request a user’s location. The location provided by the user can be determined using GPS, WIFI, IP Geolocation, etc. To protect the user’s privacy, it will first ask for permission to locate the device, and if the user grants permission, we can locate the device.
Geolocation API
In Javascript, we have a navigator.geolocation object, which is used to locate devices. We’ll be using the getCurrentPosition method.
- getCurrentPosition(): This method is used to get the user’s current location. This method will return an object which contains pieces of information like latitude, longitude, accuracy in meters.
So let’s get started..
Note: We need to wrap our code in an if block since not all browsers support the Geolocation Web API.
If the browser supports it, you can request the user’s location from the Geolocation API using the getCurrentPosition function.
The getCurrentPosition() method has two parameters, the first one is the returned coordinate object and the second one is the error object if there is any.
If we run the above code using the run button present at the top menu of the code block, We will be asked for permission by the site that the site wants our location. If we click the allow button, the site can access our location, and the successCallBack() function will be called, and if we click on the block button, the site can’t access our location failureCallBack() function will be called.
The result will look like this:
With this data, it is hard to identify the user’s location in a human-readable format so you’ll need to use a Geocoding service to translate these to real locations.
To convert this data to a human-readable address, we have to do something like reverse geocoding.
There are several Geocoding providers. For the tutorial, I am using OpenCage Geocoding API (free but an account and API key are required for requests) to translate the longitude and latitude values.
Just go to the site -> login/signup and get your API key. Once you have your API key then you can place it in your code.
The output will look like this:
Also, there is a components
property inside each item in the results array that gives you direct access to each part of the location.
You can find the code repo here: https://github.com/nisar1406/geoLocation-api-js