Search code examples
javascriptjquerygeolocationweather

Geolocation API not working


I am building a weather page and I need to grab the user location in order to get the weather data.

if ((navigator.geolocation)&&(location!=null)) {
    var locations = null;
    window.navigator.geolocation.getCurrentPosition(function(position){
        var latitude  = position.coords.latitude;
        var longitude = position.coords.longitude;
        locations = latitude+'/'+longitude;
        show_all_weather_components();  
        console.log("1");
    }); 
}
/* If location is not found the set default location as USDC0001, which is default code for washington DC. */

var locations= !locations?"USDC0001":locations;
console.log("2");

I am getting 2 first in my console. ie. It is always setting default address rather than the user actual address. I know it sounds ridiculous but is there some way to avoid the "non-blocking" mode of the code here. Or is there some other way to grab the user location. I tried the ip database Api as well, but it didn't worked with precision.

At one point I thought of to put a delay just below the if condition part, but Due to different modules of this weather app, my page is already very slow. Any Idea will be appreciated. Thank you


Solution

  • You have to use the other arguments of getCurrentPosition. Here is an example:

    <!DOCTYPE html>
    <html>
    <head>
      <title>Test</title>
    </head>
    <body>
      <div id="result"></div>
      <script>
         var result = document.getElementById('result');
         if (navigator.geolocation && location != null) {        
           window.navigator.geolocation.getCurrentPosition(function(position){
             result.text = position.coords.latitude + '/' + position.coords.longitude;
           }, function(error) {           
             switch(error.code) {
               case error.PERMISSION_DENIED:
                 result.innerHTML = "Denied request for Geolocation."
                 break;
               case error.POSITION_UNAVAILABLE:
                 result.innerHTML = "Location unavailable."
                 break;
              case error.TIMEOUT:
                 result.innerHTML = "Location request timed out." 
                 break;
              case error.UNKNOWN_ERROR:
                 result.innerHTML = "An unknown error occurred."
                 break;
             }
           }, { timeout: 1000, maximumAge: 1000 }); 
         }
      </script>
    </body>