我想创建一个react native expo-cli地理位置跟踪系统,我已经通过expo-location(lib(获得了位置坐标。我已经将这些坐标作为字符串存储到一个变量(文本(中。现在我想在地图视图中实时显示这些坐标。我应该如何继续?
这是代码:
import React, { useState, useEffect } from 'react'; //hooks for using react features without class
import { Platform, Text, View, StyleSheet } from 'react-native'; import Device from 'expo-device';
import * as Location from 'expo-location'; //expo lib to get location coordinates
export default function App() { const [location, setLocation] = useState(null);
const [errorMsg, setErrorMsg] = useState(null);
useEffect(() => {
(async () => {
if (Platform.OS === 'android' && !Device.isDevice) {
setErrorMsg(
'Try it on your device!'
);
return;
}
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission to access location was denied');
return;
}
let location = await Location.getCurrentPositionAsync({});
setLocation(location);
})(); }, []);
let text = 'Waiting..';
if (errorMsg) {
text = errorMsg; }
else if (location) {
text = JSON.stringify(location); }
return (
<View style={styles.container}>
<Text style={styles.paragraph}>{text}</Text>
</View> ); }
const styles = StyleSheet.create({ container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
padding: 20, }, paragraph: {
fontSize: 18,
textAlign: 'center', }, });
谢谢,我自己完成了:
这是代码:
import React, { Component } from "react";
import { StyleSheet, View } from "react-native";
import MapView from "react-native-maps";
import * as Location from "expo-location";
import * as Permissions from "expo-permissions";
const LOCATION_TASK_NAME = "background-location-task";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
region: null,
error: '',
};
}
_getLocationAsync = async () => {
await Location.startLocationUpdatesAsync(LOCATION_TASK_NAME, {
enableHighAccuracy: true,
distanceInterval: 1,
timeInterval: 5000
});
// watchPositionAsync Return Lat & Long on Position Change
this.location = await Location.watchPositionAsync(
{
enableHighAccuracy: true,
distanceInterval: 1,
timeInterval: 10000
},
newLocation => {
let { coords } = newLocation;
// console.log(coords);
let region = {
latitude: coords.latitude,
longitude: coords.longitude,
latitudeDelta: 0.045,
longitudeDelta: 0.045
};
this.setState({ region: region });
},
error => console.log(error)
);
return this.location;
};
async componentWillMount() {
// Asking for device location permission
const { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status === "granted") {
this._getLocationAsync();
} else {
this.setState({ error: "Locations services needed" });
}
}
render() {
return (
<View style={styles.container}>
<MapView
initialRegion={this.state.region}
showsCompass={true}
showsUserLocation={true}
rotateEnabled={true}
ref={map => {
this.map = map;
}}
style={{ flex: 1 }}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff"
}
});