How to get city name by using geolocation ?

02 Apr, 2020
In this article, we will learn how to get the city name of the user using reverse geocoding. We will be using a 3rd party API service provider(Location IQ) to help us to convert the latitude and longitude we receive into an address.
Steps:
Get user coordinates.Get city name.
Get user coordinates.
Get city name.
Note: A LocationIQ account needs to get an API token.
index.html Getting user coordinates.
The Geolocation interface allows us to obtain the position of the user’s device.
Geolocation.getCurrentPosition() helps us to determine the user’s location and gives back a Geoposition object with the required data.
index.html
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">    <title>Geolocation - City</title></head><body>    <script src="script.js" ></script>    </body></html>
The JavaScript file contains two functions, getCoordinates() & getCity()
getCoordinates() Function:The Geolocation interface allows us to obtain the position of the users device.Geolocation.getCurrentPosition() helps us to determine user’s location and gives back a Geoposition object with required data.Refer this link for complete info on Geolocation using JS.getCity() Function:We need a LocationIQ token to proceed.XMLHttpRequest (XHR) is an API object whose methods lets us transfer data between a web browser and a web server.Despite the name, it can be used along with HTTP and other protocols as well. And the data to be retrieved can be not just XML but also JSON, HTML or plain text.xhr.readyState == 4 && xhr.status == 200 indicates that the data is received and loaded properly.Since the data we receive is a JSON object, we can use dot notation to get the value of the attributes.
getCoordinates() Function:The Geolocation interface allows us to obtain the position of the users device.Geolocation.getCurrentPosition() helps us to determine user’s location and gives back a Geoposition object with required data.Refer this link for complete info on Geolocation using JS.
The Geolocation interface allows us to obtain the position of the users device.
Geolocation.getCurrentPosition() helps us to determine user’s location and gives back a Geoposition object with required data.
Refer this link for complete info on Geolocation using JS.
getCity() Function:We need a LocationIQ token to proceed.XMLHttpRequest (XHR) is an API object whose methods lets us transfer data between a web browser and a web server.Despite the name, it can be used along with HTTP and other protocols as well. And the data to be retrieved can be not just XML but also JSON, HTML or plain text.xhr.readyState == 4 && xhr.status == 200 indicates that the data is received and loaded properly.Since the data we receive is a JSON object, we can use dot notation to get the value of the attributes.
We need a LocationIQ token to proceed.
XMLHttpRequest (XHR) is an API object whose methods lets us transfer data between a web browser and a web server.
Despite the name, it can be used along with HTTP and other protocols as well. And the data to be retrieved can be not just XML but also JSON, HTML or plain text.
xhr.readyState == 4 && xhr.status == 200 indicates that the data is received and loaded properly.
Since the data we receive is a JSON object, we can use dot notation to get the value of the attributes.
script.js
// Step 1: Get user coordinatesfunction getCoordintes() {    var options = {        enableHighAccuracy: true,        timeout: 5000,        maximumAge: 0    };      function success(pos) {        var crd = pos.coords;        var lat = crd.latitude.toString();        var lng = crd.longitude.toString();        var coordinates = [lat, lng];        console.log(`Latitude: ${lat}, Longitude: ${lng}`);        getCity(coordinates);        return;      }      function error(err) {        console.warn(`ERROR(${err.code}): ${err.message}`);    }      navigator.geolocation.getCurrentPosition(success, error, options);}  // Step 2: Get city namefunction getCity(coordinates) {    var xhr = new XMLHttpRequest();    var lat = coordinates[0];    var lng = coordinates[1];      // Paste your LocationIQ token below.    xhr.open('GET', "https://us1.locationiq.com/v1/reverse.php?key=YOUR_PRIVATE_TOKEN&lat=" +    lat + "&lon=" + lng + "&format=json", true);    xhr.send();    xhr.onreadystatechange = processRequest;    xhr.addEventListener("readystatechange", processRequest, false);      function processRequest(e) {        if (xhr.readyState == 4 && xhr.status == 200) {            var response = JSON.parse(xhr.responseText);            var city = response.address.city;            console.log(city);            return;        }    }}  getCoordintes();
Output:
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?