Я относительно новичок в React Expo, и в настоящее время я работаю над личным проектом, где я хотел бы:
a. Попросите у пользователя разрешение предоставить доступ к местоположению (OK).
b. Когда кнопка нажимается, начните отслеживать, как далеко человек прошел/запустил, и она должна прекратить отслеживание, когда нажата кнопка «Остановка» (OK).
Для тестирования я использую React Expo Go Go Go Go Однако, когда я запускаю его по телефону, расстояние, которое я прошел/запустил, не является точным, и когда я остановлен, он все еще, кажется, увеличивает расстояние. Пожалуйста, я был бы признателен за любую помощь. < /P>
У меня есть следующий код: < /p>
const MIN_MOVEMENT_THRESHOLD = 1; // Ignore movements less than 1 meter
// Haversine formula to calculate distance in meters
const getDistance = (lat1: number, lon1: number, lat2: number, lon2: number) => {
const R = 6371000; // Radius of Earth in meters
const toRad = (angle: number) => (angle * Math.PI) / 180;
const dLat = toRad(lat2 - lat1);
const dLon = toRad(lon2 - lon1);
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
};
export function RouteMapScreen({ route }: { route: any }) {
const mapInView = route.params.chosenMap;
// const pathLength = mapInView.pathLengthRoute;
//const [dashOffset, setDashOffset] = useState(pathLength * (1 - mapInView.startPoint));
const [isTracking, setIsTracking] = useState(false);
const [totalDistance, setTotalDistance] = useState(0);
const lastLocationRef = useRef(null); // Persist previous location
useEffect(() => {
let locationSubscription: Location.LocationSubscription | null = null;
const startTracking = async () => {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== "granted") {
console.log("Permission to access location was denied");
return;
}
locationSubscription = await Location.watchPositionAsync(
{
accuracy: Location.Accuracy.Highest, // Highest accuracy for better precision
distanceInterval: 1, // Update more frequently for better accuracy
timeInterval: 1000 // Update every second
},
(location) => {
console.log("Current location:", location.coords);
// Ignore updates when stationary or moving too slowly
if (location.coords.speed !== null && location.coords.speed < 0.5) {
console.log("User is stationary or moving too slowly, ignoring movement.");
return;
}
if (lastLocationRef.current) {
const distance = getDistance(
lastLocationRef.current.coords.latitude,
lastLocationRef.current.coords.longitude,
location.coords.latitude,
location.coords.longitude
);
// Only add the distance if it's greater than the threshold
if (distance > MIN_MOVEMENT_THRESHOLD) {
setTotalDistance((prev) => prev + distance);
console.log("Distance added:", distance);
}
}
lastLocationRef.current = location; // Store last location
// setDashOffset((prevOffset) => Math.max(prevOffset - 10, 0));
}
);
};
if (isTracking) {
startTracking();
}
console.log("Tracking status:", isTracking);
return () => {
if (locationSubscription) {
locationSubscription.remove();
console.log("Tracking stopped.");
}
};
}, [isTracking]);
return (
INVITE
Run
setIsTracking(false)}>
END
Distance: {totalDistance.toFixed(2)} meters
setIsTracking(true)}>
START
);
}
Подробнее здесь: https://stackoverflow.com/questions/794 ... react-expo
Как прослушать движение пользователя и считать их расстояние в React Expo ⇐ Javascript
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Сходство строк с Python + Sqlite (расстояние Левенштейна/расстояние редактирования)
Anonymous » » в форуме Python - 0 Ответы
- 29 Просмотры
-
Последнее сообщение Anonymous
-