capacitor-community / background-geolocation

A Capacitor plugin that sends you geolocation updates, even while the app is in the background.
MIT License
188 stars 57 forks source link

Cannot read property 'addWatcher' of undefined #20

Closed psanxiao closed 3 years ago

psanxiao commented 3 years ago

I'm developing an ionic app with React and capacitor (v2).

Installed this plugin as Readme said. Imported like:

 import {Plugins} from "@capacitor/core";
const {BackgroundGeolocation} = Plugins;

and used as:

this.watcher_id = BackgroundGeolocation.addWatcher(
            {
                backgroundTitle: "Tracking...",
                requestPermissions: false,
                stale: false,
            },
            (location, geolocationError) => {
                if (geolocationError) {
                    console.log("getting geolocation error", geolocationError);
                    this.setState({
                        lastCoords: null,
                        errorMessage: geolocationError.message,
                    });
                } else {
                    console.log("getting geolocation", location);
                    this.setState(prevState => {
                        return {
                            isLocationFound: true,
                            points: [...prevState.points, location],
                            lastCoords: location,
                            errorMessage: null,
                        };
                    });
                }
            }
        );

But I get this in execution:

capacitor-runtime.js:358 TypeError: Cannot read property 'addWatcher' of undefined at n.value (main.b2f4cf63.chunk.js:1) at n. (main.b2f4cf63.chunk.js:1) at fo (4.cef1bb18.chunk.js:2) at ps (4.cef1bb18.chunk.js:2) at Du (4.cef1bb18.chunk.js:2) at t.unstable_runWithPriority (4.cef1bb18.chunk.js:2) at Ui (4.cef1bb18.chunk.js:2) at Tu (4.cef1bb18.chunk.js:2) at mu (4.cef1bb18.chunk.js:2) at 4.cef1bb18.chunk.js:2

I think is related with issue #17 but it was closed without answer...

diachedelic commented 3 years ago

I can only assume the plugin was not successfully registered. Maybe try running npx cap sync and rebuilding.

Note that the plugin is not available on the web platform.

psanxiao commented 3 years ago

It seems the problem was it's necessary to import the plugin in the MainActivity java class by hand, despite of using capacitor to build the android App. It's working now so I'm closing the issue.