演示

Geolocation

getCurrentPosition, watchPosition, clearWatch — 用完务必 clearWatch。

Geolocation

getCurrentPosition, watchPosition, clearWatch — 用完务必 clearWatch。

  • Methods: getCurrentPosition(), watchPosition(cb), clearWatch(id)
  • Always clearWatch when the watcher is no longer needed
TSXGeolocation — one-shot
1import { Geolocation, toast } from "@quan-erp/shared-frontend-core"; 2 3export async function readCurrentPosition() { 4 try { 5 const pos = await Geolocation.instance.getCurrentPosition(); 6 return { 7 lat: pos.coords.latitude, 8 lng: pos.coords.longitude, 9 accuracy: pos.coords.accuracy, 10 }; 11 } catch (e) { 12 toast.error((e as Error).message ?? "Location failed"); 13 return null; 14 } 15}
TSXGeolocation — watch (React)
1import { useEffect, useState } from "react"; 2import { Geolocation } from "@quan-erp/shared-frontend-core"; 3 4export function LiveLocation() { 5 const [coords, setCoords] = useState<{ lat: number; lng: number } | null>( 6 null, 7 ); 8 9 useEffect(() => { 10 const geo = Geolocation.instance; 11 let watchId: string | number | undefined; 12 13 void (async () => { 14 watchId = await geo.watchPosition((p) => { 15 setCoords({ 16 lat: p.coords.latitude, 17 lng: p.coords.longitude, 18 }); 19 }); 20 })(); 21 22 return () => { 23 if (watchId != null) geo.clearWatch(watchId); 24 }; 25 }, []); 26 27 if (!coords) return <span>Locating…</span>; 28 return ( 29 <span> 30 {coords.lat.toFixed(5)}, {coords.lng.toFixed(5)} 31 </span> 32 ); 33}