最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - navigator.geolocation.getCurrentPositionwatchPosition is not working in android 6.0 - Stack Overflow

programmeradmin0浏览0评论

Here is my javascript code :

function getLocation() { 
    //navigator.geolocation.getCurrentPosition(getCoor, errorCoor, {maximumAge:60000, timeout:30000, enableHighAccuracy:true});
    var mobile =jQuery.browser.mobile;
    var deviceAgent = navigator.userAgent.toLowerCase();
    var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
    if(mobile){
        watchLocation(function(coords) {
        var latlon = coords.latitude + ',' + coords.longitude;
         //some stuff
      }, function() {
        alert("error");
      });
    } else {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else {
            alert("error");
        }
    }
}

function watchLocation(successCallback, errorCallback) { 
    successCallback = successCallback || function(){};
    errorCallback = errorCallback || function(){}; 
    // Try HTML5-spec geolocation.
    var geolocation = navigator.geolocation; 
    if (geolocation) {
        // We have a real geolocation service. 
        try {
          function handleSuccess(position) {
            alert("position:"+position.coords); 
            successCallback(position.coords);
          }  
          geolocation.watchPosition(handleSuccess, errorCallback, {
            enableHighAccuracy: true,
            maximumAge: 5000 // 5 sec.
          }); 
        } catch (err) { 
            errorCallback();
        }
    } else {  
        errorCallback();
    }
}

I have tried both getCurrentPosition and watchPosition.

It's reaching errorCalback() method when control es to geolocation.watchPosition line.

I am testing in Motorola G 2nd Gen with Android 6 and Google chrome browser and opera mini.

Update 1: When I put alert in error call back function I got error:1; message:Only Secure origins are allowed(see:link).

    navigator.geolocation.getCurrentPosition(showPosition, function(e)
    {  alert(e); //alerts error:1; message:Only Secure origins are allowed(see:  )
       console.error(e);
    })

Update 2: With the help from g4s8 I am able to findout that the error is because of insecure URL. i.e only accessing with http instead of https.But then also I bypassed that in browser by clicking advanced button.But it will prompt for Do you want to allow location, which I don't want..is there any way to access location without prompting it?

Here is my javascript code :

function getLocation() { 
    //navigator.geolocation.getCurrentPosition(getCoor, errorCoor, {maximumAge:60000, timeout:30000, enableHighAccuracy:true});
    var mobile =jQuery.browser.mobile;
    var deviceAgent = navigator.userAgent.toLowerCase();
    var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
    if(mobile){
        watchLocation(function(coords) {
        var latlon = coords.latitude + ',' + coords.longitude;
         //some stuff
      }, function() {
        alert("error");
      });
    } else {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else {
            alert("error");
        }
    }
}

function watchLocation(successCallback, errorCallback) { 
    successCallback = successCallback || function(){};
    errorCallback = errorCallback || function(){}; 
    // Try HTML5-spec geolocation.
    var geolocation = navigator.geolocation; 
    if (geolocation) {
        // We have a real geolocation service. 
        try {
          function handleSuccess(position) {
            alert("position:"+position.coords); 
            successCallback(position.coords);
          }  
          geolocation.watchPosition(handleSuccess, errorCallback, {
            enableHighAccuracy: true,
            maximumAge: 5000 // 5 sec.
          }); 
        } catch (err) { 
            errorCallback();
        }
    } else {  
        errorCallback();
    }
}

I have tried both getCurrentPosition and watchPosition.

It's reaching errorCalback() method when control es to geolocation.watchPosition line.

I am testing in Motorola G 2nd Gen with Android 6 and Google chrome browser and opera mini.

Update 1: When I put alert in error call back function I got error:1; message:Only Secure origins are allowed(see:link).

    navigator.geolocation.getCurrentPosition(showPosition, function(e)
    {  alert(e); //alerts error:1; message:Only Secure origins are allowed(see:  )
       console.error(e);
    })

Update 2: With the help from g4s8 I am able to findout that the error is because of insecure URL. i.e only accessing with http instead of https.But then also I bypassed that in browser by clicking advanced button.But it will prompt for Do you want to allow location, which I don't want..is there any way to access location without prompting it?

Share Improve this question edited May 23, 2017 at 12:09 CommunityBot 11 silver badge asked Oct 26, 2016 at 7:32 Prasanna Kumar H APrasanna Kumar H A 3,4416 gold badges27 silver badges52 bronze badges 6
  • 1 Did you try to add 2nd param (error callback) to getCurrentPosition method? navigator.geolocation.getCurrentPosition(showPosition, function(e) {console.error(e);}) – Kirill Commented Oct 28, 2016 at 9:11
  • yes...you can see the 2nd line which is mented...errorCoor is that callback function... – Prasanna Kumar H A Commented Oct 28, 2016 at 9:37
  • Can you print error to console and add error message to this question? It may contain useful information. e.g. PositionError {code: 1, message: "User denied Geolocation"} – Kirill Commented Oct 28, 2016 at 9:44
  • 1 You can cannect to android device from google chrome. See this link developers.google./web/tools/chrome-devtools/… – Kirill Commented Oct 28, 2016 at 9:48
  • 1 In this case you can show error code and message in alert: function (err) {alert("error: " + err.code + "; message: " + err.message);} – Kirill Commented Oct 28, 2016 at 9:55
 |  Show 1 more ment

1 Answer 1

Reset to default 5 +50

Your page should be served over https to access geolocation API.

See Geolocation API Removed from Unsecured Origins

Starting with Chrome 50, Chrome no longer supports obtaining the user's location using the HTML5 Geolocation API from pages delivered by non-secure connections

...

It is an important issue as it will directly impact any site that requires use of the geolocation API and is not served over https

To fix this serve your page over https or on localhost.


Thank you...Is there any way to bypass it??

You can try to use some geolocation services, e.g. geoip2, Geolocation request


how to use them? can you show an example?? from those two can i access user location without knowing them?

GeoIP2 detect you location by ip address. You can obtain country (geoip2.country()) and city (geoip2.city) with js lib:

<script src="//js.maxmind./js/apis/geoip2/v2.1/geoip2.js" type="text/javascript"></script>

Here https://dev.maxmind./geoip/geoip2/javascript/ you can find full documentation.

Google maps geolocation is google service, so you need to get api key first. Then you can send POST request with json parameters to https://www.googleapis./geolocation/v1/geolocate?key=API_KEY and get the response:

{
  "location": {
    "lat": 51.0,
    "lng": -0.1
  },
  "accuracy": 1200.4
}

where location is the user’s estimated latitude and longitude, in degrees, and accuracy is the accuracy of the estimated location, in meters.

Full json parameters defenition you can find in "Request body" section here https://developers.google./maps/documentation/geolocation/intro#overview

Also you can find useful those answers: getCurrentPosition() and watchPosition() are deprecated on insecure origins


using IP it provides only country and city..??

Yes, only this.

will it provide physical location like how getCurrent Position provides??

No, you can't get physical location, because it can be accessed only via gelocation API, that was restricted in insecure context.

Also you have one more option. You can host only one page (that access geolocation API) on https server, and redirect from this page to your http site with user location in get parameters.

/* https page */
navigator.geolocation.getCurrentPosition(function (result) {
    window.location.href = "http://your.site./http-page?lat=" + result.latitude + "&long=" + result.longitude;
});
发布评论

评论列表(0)

  1. 暂无评论