transistorsoft / react-native-background-geolocation

Sophisticated, battery-conscious background-geolocation with motion-detection
http://shop.transistorsoft.com/pages/react-native-background-geolocation
MIT License
2.66k stars 426 forks source link

Can't get the current position while moving #2196

Closed thur-c closed 3 weeks ago

thur-c commented 3 weeks ago

Can't get the current position while moving

interface LocationContextType { currentLocation: Location | undefined; }

interface LocationContextProps { children: React.ReactNode; }

export const LocationContext = createContext({} as LocationContextType);

export function LocationContextProvider({ children }: LocationContextProps) { const {uid, token} = useContext(UserContext); const [enabled, setEnabled] = useState(false); const [currentLocation, setCurrentLocation] = useState<Location | undefined>();

async function configBackgroundGeolocation() {
    await BackgroundGeolocation.ready({
        desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
        distanceFilter: 0,
        stopTimeout: 1,
        debug: true,
        logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
        disableMotionActivityUpdates: true,
        stopOnTerminate: false,
        startOnBoot: true,
        locationUpdateInterval: 1000,
        fastestLocationUpdateInterval: 1000,
        useSignificantChangesOnly: false,
        disableElasticity: true,
        preventSuspend: true,
        url: 'http://my.server.com',
        params: {
            user_id: 123,
        },
        headers: {
            'my-auth-token': 'secret-key',
        },
    }).then((state) => {
        setEnabled(true);

    }).catch((error) => {
        console.error(error);
    });
}

useEffect(() => {
    try {
        configBackgroundGeolocation();
    } catch (error) {
        console.error(error);
    } finally {
        console.log('Finished processing background geolocation');
    }
}, []);

 async function sendLocation(body: Location) {
    if (body && uid && token) {
        handleSetCurrentLocation(body);
        const response: AxiosResponse = await updateLocation(uid, token, body);
        handleResponse(response);
    }else{
        console.log('Missing uid, token or body');
    }
}

function handleResponse(response: AxiosResponse){
    if(response.status === 200){
        console.log('Response: ', response.status);
    }else{
        console.log('Error sending location: ', response.status);
    }
}

useEffect(() => {
    try {
        if (enabled) {
            BackgroundGeolocation.start().then(() => {
                BackgroundGeolocation.onLocation((location: Location) => {
                    handleSetCurrentLocation(location);
                    const objectToSend = {
                        ...location,
                        now: Date.now(),
                    };
                    sendLocation(objectToSend);
                });

                BackgroundGeolocation.onHeartbeat((heartbeatEvent) => {
                    const objectToSend = {
                        ...heartbeatEvent.location,
                        now: Date.now(),
                    };
                    sendLocation(objectToSend);
                    handleSetCurrentLocation(heartbeatEvent.location);

                });
            });

        } else {
            BackgroundGeolocation.stop();
        }
    } catch (error) {
        console.log(error);
    }
}, [enabled]);

 function handleSetCurrentLocation(location: Location){
     setCurrentLocation(location);
}

return (
    <LocationContext.Provider value={{currentLocation}}>
        {children}
    </LocationContext.Provider>
);

}



## Expected Behavior
It should get the position when it starts moving, but it doesn't return anything

## Actual Behavior
When the emulator starts moving, the current location doesn't update 

## Steps to Reproduce
<!--- reproduce this issue; include code to reproduce, if relevant -->
1.
2. 
3. 
4. 

## Context
<!--- What were you trying to do? -->

## Debug logs
<!-- include iOS / Android logs
- ios XCode logs,
- use #getLog #emailLog methods (@see docs)
- Android: $ adb logcat -s TSLocationManager
-->

<details><summary>Plugin Logs</summary>

``` <!-- Syntax highlighting:  DO NOT REMOVE -->
christocracy commented 3 weeks ago

That’s correct.

This is explained in the wiki “Debugging”.

the plug-in doesn’t detect movement with location changes. It detects movement via Motion API and the Motion api doesn’t operate in the simulator.

In the emulator, you must manually call .changePace(true) to tell the plug-in to turn on location-services and begin receiving location updates.

the best way to test this plug-in is with a real device with real movement.

christocracy commented 3 weeks ago

Btw, don’t wait until .start() resolves to add listeners.

add them before. Adding listeners is like wiring up speakers to a stereo. You don’t wait until you turn your stereo on to hook up your speakers (you might miss the start of the song). You do it once (when your app boots).

adding listeners (eg .onLocation) does nothing more than add a callback function to an Array. It is a completely harmless and inexpensive action.