getting users geolocation via html5 and javascript

后端 未结 8 1862
陌清茗
陌清茗 2020-12-14 10:45

I am trying to get the users geolocation via the html5 geolcation api, and i use the following snippet for it:

if (navigator.geolocation) {
    var timeoutVa         


        
8条回答
  •  一向
    一向 (楼主)
    2020-12-14 11:22

    If there is a timeout or the user denies the request, I would set a default location like New York, NY (40.7142, -74.0064). If a user denies a request, they have to also expect that you won't know their location so choosing an intelligible default is the next best thing.

    Using a default without changing your code much can be accomplished by calling displayPosition({coords: {latitude: 40.7142, longitude: -74.0064}}) in two places:

    if (navigator.geolocation) {
        var timeoutVal = 10 * 1000 * 1000;
        navigator.geolocation.getCurrentPosition(
            displayPosition, 
            displayError,
            { enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
        );
    }
    else {
        displayPosition({coords: {latitude: 40.7142, longitude: -74.0064}})
    }
    ....
    function handleError(error){
        switch(error.code)
        {
            case error.PERMISSION_DENIED: alert("User did not share geolocation data");break;  
            case error.POSITION_UNAVAILABLE: alert("Could not detect current position");break;  
            case error.TIMEOUT: alert("Retrieving position timed out");break;  
            default: alert("Unknown Error");break;  
        }
        displayPosition({coords: {latitude: 40.7142, longitude: -74.0064}});
    }
    

    On http://nearbytweets.com I use a "queue" of functions for finding a user's location, looping through the queue until one of them finds a valid location. The last function returns New York, NY, which means all other attempts have failed. Here's a sample of the code modified slightly:

    var position_finders = [                                                                                                                                                                                                              
        function () {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(check_position, check_position);
                return;
            }   
            check_position();
        },  
        function () {
            check_position(JSON.parse(localStorage.getItem('last_location')));
        },  
        function () {
            $.ajax({
                url: 'http://www.google.com/jsapi?key=' + google_api_key,
                dataType: 'script',
                success: check_position
            }); 
        },  
        function () {
            check_position({latitude: 40.7142, longitude: -74.0064}, true);
        }   
    ],
    
    check_position = function (pos, failed) {
        pos = pos || {}; 
        pos = pos.coords ? 
            pos.coords :
            pos.loader ?
            pos.loader.clientLocation :
            pos;
    
        if (typeof pos.latitude === 'undefined' || typeof pos.longitude === 'undefined') {
            position_finders.shift()();
            return;
        }   
    
        localStorage.setItem('last_location', JSON.stringify(pos));
    
        // using your code, I would call this:
        displayPosition(pos);
    };
    
    check_position();
    

    Here's what each position_finder does:

    1. Tries navigator.geolocation.
    2. Tries pulling their last location from localStorage
    3. Uses Google Loader to find location via I.P.
    4. Uses New York, NY

提交回复
热议问题