Open In App

How to get city name by using geolocation ?

Last Updated : 02 Apr, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. Get user coordinates.
  2. 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()

  1. 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.
  2. 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.

script.js




// Step 1: Get user coordinates
function 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 name
function getCity(coordinates) {
    var xhr = new XMLHttpRequest();
    var lat = coordinates[0];
    var lng = coordinates[1];
  
    // Paste your LocationIQ token below.
    xhr.open('GET', "
    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:



Similar Reads

How to get Geolocation using PHP-cURL from IP Address ?
Geolocation refers to the identification of the geographical location of a user or computer device. In this article, we will create a web page where the user can enter the IP Address of any device, and then the server will provide Geolocation of the IP address fetching the following details using the IP Geolocation API. Continent NameCountry NameCo
2 min read
How to Promisify geolocation API to get current position using JavaScript ?
In this article, we are going to use Promisify geolocation API into Promise-based API. Prerequisite: JavaScript Promise Approach: As we know the navigator.geolocation.getCurrentPosition is a callback-based API, so we can easily convert it into a Promise-based API. To promisify the geolocation API, we will get the user's current position from the br
3 min read
Get current Geolocation of user using React-Geolocated
In some situations, applications need to access the current location properties of the user. Location properties include latitude, longitude, and some more about the current location of the user. From the Location properties, the user can know the current geolocation of the user. Approach:Geolocation Availability Check:The component verifies if geo
2 min read
What is the purpose of using the Geolocation API ?
HTML Geolocation is used to get the geographical position of a user. Due to privacy concerns, this position requires user approval. Geo-location in HTML5 is used to share the location with some websites and be aware of the exact location. It is mainly used for local businesses, and restaurants, or showing locations on the map. It uses JavaScript to
1 min read
HTML DOM Navigator geolocation Property
The Navigator geolocation property is used to return a geolocation object by the browser which can be used to locate a user's position. It is a read-only property and is only available on the approval of the user since it can compromise the user's privacy. Syntax: navigator.geolocation Below program illustrates the Navigator geolocation Property :C
1 min read
HTML DOM Geolocation position Property
The Geolocation position property in HTML DOM is used to return the position of a device on Earth. The returned Coordinates object could be used for various purposes including navigation and tracking the position of the device. Return Value: position.coords: The coordinates object that has all the information of the current location.position.timest
2 min read
HTML DOM Geolocation coordinates Property
The DOM Geolocation coordinates Property in HTML is used to return the position and altitude of the device on Earth. The returned Coordinates object could be used for various purposes including navigation and tracking the position of the device. Property Values: ValuesDescriptioncoordinates.latitudeThis is the device latitude in decimal degrees.coo
2 min read
HTML DOM Geolocation coords.longitude Property
In this article, we will discuss the Geolocation longitude property. Geolocation in HTML is used to get the geographical position of a user. The getCurrentPosition() method in this geolocation returns an object on success. coords.longitude: This property will return the longitude as a decimal number Syntax: coords.longitude Example: The following H
1 min read
HTML DOM Geolocation coords.latitude Property
In this article, we will discuss the Geolocation latitude property. Geolocation in HTML is used to get the geographical position of a user. The getCurrentPosition() method, in this geolocation, returns an object on success. coords.latitude: This property will return the latitude as a decimal number. Please refer to the HTML Geolocation article for
1 min read
HTML DOM Geolocation timestamp Property
In this article, we will discuss the Geolocation timestamp property. Geolocation in HTML is used to get the geographical position of a user. The getCurrentPosition() method, in this geolocation, returns an object on success. Syntax: timestamp Return Value:- This geolocation property returns an object on success. Example: The following HTML code ret
1 min read