Checking if location services are enabled using react native

半世苍凉 提交于 2019-12-05 04:49:57

Use the "react native android location services dialog box" module for android

https://www.npmjs.com/package/react-native-android-location-services-dialog-box

install

npm install react-native-android-location-services-dialog-box --save

js

import LocationServicesDialogBox from "react-native-android-location-services-dialog-box";

LocationServicesDialogBox.checkLocationServicesIsEnabled({
  message: "Use Location ?",
  ok: "YES",
  cancel: "NO"
}).then(function(success) {
  console.log(success); // success => "enabled"
).catch((error) => {
  console.log(error.message); // error.message => "disabled"
});

I was able to solve this by displaying an error message when the location could not be retrieved.

(error) => {
        this.setState({servicesOn: false}),
        console.log(error);
      },

Do a watchPosition or getCurrentPosition, Your second argument is a callback in case of failure, and its argument is the reason it failed.

So, from there you know when and why it fails. You'll need an if for the reason if you only want to act on 'location disabled' and not 'request timed out' for example.

You can use the callback to add a flag to your state for example.

You can also try out these 2 libraries:

https://github.com/c19354837/react-native-system-setting

https://github.com/efkan/react-native-system-settings

What I have is the following: I get this error code 1 or error message: 'No location provider available.' when my phone location service is turned off.

Other time, when it times out, I get this error code 3 or error message: 'Location request timed out.'.

Thus, based on the error code and message, I display different toasts to inform the user.

You can refer to this position error doc on MDN

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!