如何使用react-native-location获取位置信息?
我在this网站上关注,但示例链接无效,我编写的代码与“用法”部分相同,但无效。我不知道为什么。
答案 0 :(得分:1)
如果只需要获取位置,则可以尝试使用here描述的现有的react native方法。我给你一个我现在测试过的例子:
componentDidMount() {
navigator.geolocation.getCurrentPosition(
position => {
console.log('geolocation: ', position);
},
error => Alert.alert(error.message),
{ enableHighAccuracy: false, timeout: 20000, maximumAge: 1000 }
);
}
只是不要忘记在 AndroidManifest.xml 中放置所需的权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
如果您在建筑物内测试应用程序,也可能什么也收不到!要查看结果,请在选项中放入enableHighAccuracy: false,
(即,看我的示例)。
结果:
使用react-native-location(已针对android测试!)
npm install-保存react-native-location react-native链接react-native-location 权限:
演示示例:
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow
*/
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
import RNLocation from 'react-native-location';
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
android:
'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
type Props = {};
export default class App extends Component<Props> {
constructor(props) {
super();
this.state = {
lat: null,
lon: null,
}
}
componentDidMount() {
RNLocation.configure({
distanceFilter: 5.0
})
RNLocation.requestPermission({
ios: "whenInUse",
android: {
detail: "coarse"
}
}).then(granted => {
if (granted) {
this.locationSubscription = RNLocation.subscribeToLocationUpdates(locations => {
console.log('locations: ', locations);
let lat = locations[0].latitude;
let lon = locations[0].longitude;
console.log('locations: ', lat, lon);
this.setState({ lat: lat, lon: lon });
})
}
})
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.instructions}>To get started, edit App.js</Text>
<Text>`lat: ${this.state.lat} lon: ${this.state.lon}`</Text>
<Text style={styles.instructions}>{instructions}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
结果:
如果仍然有问题,请检查“ 手动链接库的步骤”部分,以确保是否正确安装了evrything!