我一直在尝试向我的应用程序添加位置功能,并且我一直在尝试使用官方的 @react-native-community/geolocation 包。但它总是出错。
我已经安装了
npm install @react-native-community/geolocation
`包'@react-native-community/geolocation'似乎没有链接。确保:(设备)
我不知道下一步该做什么。
这个包在我的项目上运行良好。
首先删除
node-modules
和 yarn.lock
或 package.lock
文件。
让我们在 package.json 中添加
"@react-native-community/geolocation": "^2.0.2"
并使用yarn或npm安装所有依赖项:
yarn or npm i
现在从
Geolocation
导入 '@react-native-community/geolocation'
并使用它。
示例
export const getLocationService = async (
getCurrentLocationSuccess,
getCurrentLocationFailure,
) => {
Geolocation.getCurrentPosition(
position => {
const location = {
lat: position.coords.latitude,
long: position.coords.longitude,
};
getCurrentLocationSuccess(location);
},
error => {
getCurrentLocationFailure(error);
},
{
enableHighAccuracy: false,
timeout: 10000,
maximumAge: 10000,
},
);
};
在应用程序中的任何位置调用此函数,如下所示
import {getLocationService} from '../locations';
const getCurrentLocation = async () => {
getLocationService(getCurrentLocationSuccess,
getCurrentLocationFailure);
};
成功获取位置后
const getCurrentLocationSuccess = res => {
console.log('Single road 2 double 0:', JSON.stringify(res));
};
无法获取位置时
const getCurrentLocationFailure = error => {
console.log('error', error);
};
卸载设备上以前安装的应用程序,并在 gradlew clean 后重新运行应用程序。
希望能解决您的问题。