简体   繁体   中英

How to get the weather conditions based on the user’s current GPS location

Everything works with my code except the fact that the current location displays somewhere else. I live in Kuils River and it gives me the weather conditions for Edgemead. How do I get it for the current location where I am at? Can anyone help me with this one.

$(document).ready(function() {
  var lat, lon, api_url;

  if ("geolocation" in navigator) {
    $('#showTemp').on('click', function() {
      navigator.geolocation.getCurrentPosition(gotLocation);

      function gotLocation(position) {
        lat = position.coords.latitude;
        lon = position.coords.longitude;

        api_url = 'http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&units=metric&appid=b231606340553d9174136f7f083904b3';
        APPID: '53f9d8e4213222cf517d86dc406d67fc'

        $.ajax({
          url: api_url,
          method: 'GET',
          success: function(data) {
            var tempr = data.main.temp;
            var location = data.name;
            var desc = data.weather.description;
            $('#result').text(tempr + '°' + location);
          }
        });
      }
    });
  } else {
    alert('Your browser doesnt support geolocation. Sorry.');
  }
});

I noticed an error at:

api_url = 'http://api.openweathermap.org/data/2.5/weather?lat=' +
          lat + '&lon=' + 
          lon + '&units=metric&appid=b231606340553d9174136f7f083904b3';
          APPID: '53f9d8e4213222cf517d86dc406d67fc'

//

The appid is there twice. Can you give me the coordinates (lat, lon) you're expecting? You should be able to plug in the url directly in your browser to see what you're getting. Have you tried that?

The location is based on where your Internet connection "Break Out", this code seems to use the browser/HTML5 getCurrentPosition() API.

Replace this with the actual GPS values and it will be more accurate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM