Search code examples
javascripthtmlw3c-geolocation

How to detect the status of the element navigation in js?


I need to get users latitude and longitude from browser, but on most of browsers are some restrictions that doesn't let to do it. How to tell users that his geolocation is off or it simply doesn't support it?

I tried something like this, but neither ipad or safari on my mac prompt anything.

if (navigator.geolocation)
    navigator.geolocation.getCurrentPosition(success);
else
    alert('not supported');

Solution

  • DEMO: http://jsfiddle.net/7sRdS/

    if (navigator.geolocation) { 
        navigator.geolocation.getCurrentPosition(function(position) {  
            // ... 
        }, function(error) {
            //error handling
            switch(error.code) {
                case error.PERMISSION_DENIED:
                  //User denied the request for Geolocation.             
                  break;
                case error.POSITION_UNAVAILABLE:
                  //Location information is unavailable.
                  break;
                case error.TIMEOUT:
                  //The request to get user location timed out.
                  break;
                case error.UNKNOWN_ERROR:
                  //An unknown error occurred.
                  break;
            }
            alert("Geolocation error: " + error.code);
        },
        {
            timeout:10000 //10s
        });
    } else {
        alert("Geolocation services are not supported by your browser.");
    }