简体   繁体   中英

JS - Geolocation API not working on mobile even on HTTPS

I'm using Geolocation API to get the user current location and it works fine on desktop. On mobile (I'm testing on Android 10, Chrome) it doesn't ask the user for location permission, so of course I can't get what I need.

I'm developing on a local Apache web server, with HTTP. I've tried with HTTPS by exposing my localhost with Ngrok (it can returns HTTP and HTTPS both), but still not working.

That's the JS code:

var lng;
var lat;

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(getPosition);
}

function getPosition(position) {
  lng = position.coords.longitude;
  lat = position.coords.latitude;

  // Some other code here (does not affect the API)
}

EDIT

I have also checked my phone settings and chrome settings and they're fine. I went some other websites that uses the same API and they actually works.

What does the error callback function return? This is where the answer should be.

var lng;
var lat;

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(getPosition, error);
}

function getPosition(position) {
  lng = position.coords.longitude;
  lat = position.coords.latitude;

  // Some other code here (does not affect the API)
}

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}

Basically, everything was fine.

I've tried this code on mobile multiple times without changing anything. I've tried it again, and suddenly it now works.

I have no idea what was happening, but without changing anything it now works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM