How do you use JavaScript to get the current city the user is in and display it in a <h2>?

Aaron Peck picture Aaron Peck · Mar 22, 2017 · Viewed 7.2k times · Source
$(document).ready(function(){
    $("#getLocation").on("click", function(){
        $.getJSON('https://geoip-db.com/json/geoip.php?jsonp=?') 
        .done (function(location) {
            $('#city').html(location.city);             
        });
    });
});

This is the current JavaScript I've been using, and here is the link to the CodePen I'm using it for. I'm using the location of the users city to find the weather of that city as well.

I've read on multiple sites about how to use several different API's to get the users city location, but non have worked in my project. Thanks for the help, in advance.

Answer

Clement picture Clement · Mar 22, 2017

To elaborate on my previous answer, a cleaner and more vanilla JavaScript way to get the coordinates is like so.

This is just a few short lines longer and the benefits are massive:

  1. Don't have to include jQuery library, which is massive and slows down page load times
  2. This means you won't have to rely on a HEAVY EXTERNAL API to make AJAX calls for the same data (and other useless API-specific info e.g. requestID) and will seriously streamline your application.
  3. Avoids the use of many callbacks and thus avoids callback hell.

See image below for results. Super lightweight and fast. For more detailed information, have a look at MDN - Using Geolocation.

if ("geolocation" in navigator) {
    // Do something with coordinates returned
    function processCoords(position) {
        let latitude = position.coords.latitude;
        let longitude = position.coords.longitude;
        let first_div = document.querySelector('div');
        let el_h2 = document.createElement('h2');

        // Set h2 text as coordinates
        el_h2.innerText = `Latitude: ${latitude}, Longitude: ${longitude}`;

        // Append h2 to document
        first_div.appendChild(el_h2);
    }

    // Fetch Coordinates
    navigator.geolocation.getCurrentPosition(processCoords);
}

To get the City:

It's usually best practice to store the coordinates only in your db and then make separate city requests when required. This makes things easier when you want to implement say a Map View on Mobile or Desktop, which all use coordinates rather than names for plots.

You can use the Google Maps API and passing in the LatLong data directly. Someone has created a gist on how to do it here.

Benefit of using GMaps instead of Geo-IP:

  1. Google Maps API is heavily, heavily, heavily optimised. From faster servers to better-written code. You can also import a specific part of the GMaps API so you can cut down on your source code size. All of this adds up to a much faster experience.
  2. GMaps can be assumed to be around for longer than a 3rd party site like Geo-Ip.

enter image description here