JS - Geolocation API not working on mobile even on HTTPS

Viewed 347

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.

2 Answers

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.

Related