最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论
$(document).ready(function(){
    $("#getLocation").on("click", function(){
        $.getJSON('.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.

$(document).ready(function(){
    $("#getLocation").on("click", function(){
        $.getJSON('https://geoip-db./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.

Share Improve this question edited Mar 22, 2017 at 22:48 dmorrow 5,7145 gold badges23 silver badges32 bronze badges asked Mar 22, 2017 at 21:51 ApeApe 111 silver badge4 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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.

I found this working

 function ipLookUp () {
$.ajax('http://ip-api./json')
    .then(
        function success(response) {
           console.log(response.city); //Users City
          console.log(response.country); //Users Country
        },
       function fail(data, status) {
            console.log('Request failed.  Returned status of',
                status);
        }
    );}ipLookUp()  
发布评论

评论列表(0)

  1. 暂无评论