navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

前端 未结 25 2058
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 13:33

So I have a pretty simple bit of JS using the navigator.geolocation.getCurrentPosition jammy.

$(document).ready(function(){
  $(\"#business-locate, #people-l         


        
25条回答
  •  情书的邮戳
    2020-11-22 14:26

    @brennanyoung's answer is great, but if you're wondering what to do in the failure case you could use an IP geolocation API such as https://ipinfo.io (which is my service). Here's an example:

    function do_something(coords) {
        // Do something with the coords here
        // eg. show the user on a map, or customize
        // the site contents somehow
    }
    
    navigator.geolocation.getCurrentPosition(function(position) { 
        do_something(position.coords);
        },
        function(failure) {
            $.getJSON('https://ipinfo.io/geo', function(response) { 
            var loc = response.loc.split(',');
            var coords = {
                latitude: loc[0],
                longitude: loc[1]
            };
            do_something(coords);
            });  
        };
    });
    

    See https://ipinfo.io/developers/replacing-getcurrentposition for more details.

提交回复
热议问题