探索 React Native 地理定位神器:react-native-location
import React, { useEffect, useState } from 'react';
import { Text, View } from 'react-native';
import RNLocation, { GeojsonPoint } from 'react-native-location';
const App = () => {
const [location, setLocation] = useState<GeojsonPoint | null>(null);
useEffect(() => {
RNLocation.getCurrentPosition({
timeout: 10000, // 10 seconds
maximumAge: 1000, // 1 second
enableHighAccuracy: true, // true = better accuracy, but slower on devices
}).then(location => {
setLocation(location);
}).catch(error => {
console.error(error);
});
}, []);
return (
<View>
{location ? (
<View>
<Text>Latitude: {location.latitude}</Text>
<Text>Longitude: {location.longitude}</Text>
</View>
) : (
<Text>Fetching location...</Text>
)}
</View>
);
};
export default App;
这段代码使用React Native和react-native-location
库来获取当前的地理位置。它首先尝试获取位置,然后将其显示在屏幕上。如果获取位置失败,它会在控制台中报错。这个例子展示了如何在React Native应用中使用地理定位功能。
评论已关闭