react native实现定位
获取定位权限
在React Native中实现定位功能需要先获取用户的位置权限。对于iOS和Android平台,权限配置方式不同。在iOS的Info.plist中添加NSLocationWhenInUseUsageDescription或NSLocationAlwaysUsageDescription键值对。在Android的AndroidManifest.xml中添加ACCESS_FINE_LOCATION或ACCESS_COARSE_LOCATION权限。
import { PermissionsAndroid } from 'react-native';
const requestLocationPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Location Permission',
message: 'App needs access to your location.',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
}
);
return granted === PermissionsAndroid.RESULTS.GRANTED;
} catch (err) {
console.warn(err);
return false;
}
};
使用Geolocation API
React Native提供了Geolocation API来获取设备的位置信息。可以通过navigator.geolocation访问。使用getCurrentPosition获取当前位置或watchPosition持续监听位置变化。
import { Geolocation } from '@react-native-community/geolocation';
Geolocation.getCurrentPosition(
position => {
console.log(position.coords.latitude, position.coords.longitude);
},
error => {
console.log(error.code, error.message);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);
const watchId = Geolocation.watchPosition(
position => {
console.log(position.coords.latitude, position.coords.longitude);
},
error => {
console.log(error.code, error.message);
}
);
// 停止监听
Geolocation.clearWatch(watchId);
使用第三方库
对于更高级的定位功能,可以使用第三方库如react-native-geolocation-service或react-native-location。这些库提供了更好的权限处理和更稳定的定位功能。
安装react-native-geolocation-service:
npm install react-native-geolocation-service
使用示例:
import Geolocation from 'react-native-geolocation-service';
const getLocation = async () => {
const hasPermission = await requestLocationPermission();
if (!hasPermission) return;
Geolocation.getCurrentPosition(
position => {
console.log(position.coords.latitude, position.coords.longitude);
},
error => {
console.log(error.code, error.message);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);
};
处理定位错误
定位可能因多种原因失败,如用户拒绝权限、设备GPS关闭或信号弱。需要妥善处理这些错误情况,提供友好的用户提示。
Geolocation.getCurrentPosition(
position => {
// 处理成功获取位置
},
error => {
switch (error.code) {
case error.PERMISSION_DENIED:
console.log('User denied the request for location access.');
break;
case error.POSITION_UNAVAILABLE:
console.log('Location information is unavailable.');
break;
case error.TIMEOUT:
console.log('The request to get location timed out.');
break;
default:
console.log('An unknown error occurred.');
}
}
);
后台定位
对于需要后台持续获取位置的应用,需要额外配置。iOS需要在Info.plist中添加UIBackgroundModes数组包含location项。Android需要声明后台服务并处理后台权限。
// 后台定位示例
const watchId = Geolocation.watchPosition(
position => {
console.log('Background location:', position.coords);
},
error => {
console.log('Background location error:', error);
},
{
distanceFilter: 10,
interval: 5000,
fastestInterval: 2000,
useSignificantChanges: false,
showsBackgroundLocationIndicator: true,
}
);





