ReactJS location access prompt on mobile device

Viewed 24

I am building an app in ReactJS that requires the user's location. In the browser (Chrome) on my PC I get a prompt once. If I decline, the prompt will not show again upon a page refresh. However, I will get the option to manually enable location.

When I open the same web page on my android phone in Chrome I neither get a prompt nor the option to enable location access manually. I have looked for solutions through Google but all of them rely on a prompt being automatically shown upon a navigator.geolocation.getCurrentPosition call, but it doesn't.

This is my code:

function getUserLocation() {
  if ("geolocation" in navigator) {
    navigator.geolocation.getCurrentPosition(
      function (position) {
        setLocationDidMount(true);
        console.log("got position");
      },
      function errorCallback(error) {
        console.log(error);
        navigator.permissions
          .query({ name: "geolocation" })
          .then(function (result) {
            if (result.state === "granted") {
              console.log(result.state);
              //If granted then you can directly call your function here
            } else if (result.state === "prompt") {
              console.log(result.state);
            } else if (result.state === "denied") {
              console.log("location access denied by user");
              //If denied then you have to show instructions to enable location
            }
            result.onchange = function () {
              console.log(result.state);
            };
          });
      },
      {
        timeout: 5000,
      }
    );
  } else {
    console.log("Not Available");
  }
}

How to handle this problem? Btw, I'm not supposed to use React-Native.

1 Answers

As is pointed out by the article shared by Sergey, mobile browsers will only handle location properly when there is an SSL certificate in place.

While causing a warning, installing a local certificate using OpenSSL did fix the problem.

Related