简体   繁体   中英

How to actively pick geo-location object arrays and perform function on it consecutively

I am actively picking up data points from geo-location using:

import * as Location from 'expo-location'

And getting distance between 2 geo-locations picked points using:

import { getDistance, getPreciseDistance } from 'geolib'

I tried having the geo-location function running continuously picking data and calculating distance between 2 points

I know this is terrible but it was the only way I could think off as a work around

  let pair = [];

  const prevVal = useRef('')

  const [location, setLocation] = useState('');

  useEffect(() => {
    prevVal.current = location;
    getNew(location)
  }, [location])


  async function getNew(k) {
    try {
      let to_location = await Location.getCurrentPositionAsync({});

      let firstSeed = {
        "latitude": to_location.coords.latitude,
        "longitude": to_location.coords.longitude,
      };

      pair.push(getPreciseDistance(firstSeed, k))
      setLocation(firstSeed)
    } catch (error) { console.log(error) }
  };

And then later I can use the method

 let finalv = pair.reduce((a, b) => a + b, 0)
 
 console.log("TOTAL DISTANCE", finalv)

Any help on the logic would be appreciated, or any efficient refactor on it

You can watch/track user location while s/he is moving with built-in Location.watchPositionAsync(options, callback) - https://docs.expo.dev/versions/latest/sdk/location/#locationwatchpositionasyncoptions-callback .

This location update is managed by the device OS and does not drain the battery quickly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM