22

None of the answers on stackoverflow worked for me. A lot of them are for Ionic 1 or those answers are deprecated or they are not working for android device.

I have seen a lot of solutions on stackoverflow about getting current location of device but non of them seems to be working for Android .

what i have tried:-

  • using geolocation.getCurrentPosition() , which is working for IOS and browser but not for Android.

  • using this.geolocation.watchPosition() , which is working for IOS and browser but not for Android.

  • using navigator.geolocation.getCurrentPosition(),which is working for IOS and browser but not for Android.

  • using fiddle solution provided by this question getCurrentPosition() and watchPosition() are deprecated on insecure origins

Anyway , all of these are deprecated by google due to :-

getCurrentPosition() and watchPosition() are deprecated on insecure origins, and support will be removed in the future. You should consider switching your application to a secure origin, such as HTTPS. See goo.gl/rStTGz for more details.

The problem with joshmorony(https://www.joshmorony.com/adding-background-geolocation-to-an-ionic-2-application/ ) solution is foreground is not working for Android physical devices but working fine for browser and ios. Background tracking is working fine , which is taking almost 50 sec to give lat & lng for the first time.

Please help me with this. I want a way to get current location in minimum time. For your info, I am using google javascript map sdk / api .

kumar kundan
  • 2,027
  • 1
  • 27
  • 41

7 Answers7

5

I tried every solution provided by all of you and others also on internet. Finally i found a solution.You can try this plugin cordova-plugin-advanced-geolocation (https://github.com/Esri/cordova-plugin-advanced-geolocation ) from ESRI . But this plugin will work for Android not IOS. For ios you can go with same old approach . i.e - using this.geolocation.getCurrentPosition(...) or this.geolocation.watchPosition(..).

Add cordova-plugin-advanced-geolocation Plugin Like this :-

cordova plugin add https://github.com/esri/cordova-plugin-advanced-geolocation.git

then Add below line at the top of Class / Component

declare var AdvancedGeolocation:any; //at the top of class

Now add these lines inside relevant function of component ( P.S. - I have included code for both Android & IOS)

//**For Android**


    if (this.platform.is('android')) {
          this.platform.ready().then(() => {
            AdvancedGeolocation.start((success) => {
              //loading.dismiss();
              // this.refreshCurrentUserLocation();
              try {
                var jsonObject = JSON.parse(success);
                console.log("Provider " + JSON.stringify(jsonObject));
                switch (jsonObject.provider) {
                  case "gps":
                    console.log("setting gps ====<<>>" + jsonObject.latitude);

                    this.currentLat = jsonObject.latitude;
                    this.currentLng = jsonObject.longitude;
                    break;

                  case "network":
                    console.log("setting network ====<<>>" + jsonObject.latitude);

                    this.currentLat = jsonObject.latitude;
                    this.currentLng = jsonObject.longitude;

                    break;

                  case "satellite":
                    //TODO
                    break;

                  case "cell_info":
                    //TODO
                    break;

                  case "cell_location":
                    //TODO
                    break;

                  case "signal_strength":
                    //TODO
                    break;
                }
              }
              catch (exc) {
                console.log("Invalid JSON: " + exc);
              }
            },
              function (error) {
                console.log("ERROR! " + JSON.stringify(error));
              },
              {
                "minTime": 500,         // Min time interval between updates (ms)
                "minDistance": 1,       // Min distance between updates (meters)
                "noWarn": true,         // Native location provider warnings
                "providers": "all",     // Return GPS, NETWORK and CELL locations
                "useCache": true,       // Return GPS and NETWORK cached locations
                "satelliteData": false, // Return of GPS satellite info
                "buffer": false,        // Buffer location data
                "bufferSize": 0,         // Max elements in buffer
                "signalStrength": false // Return cell signal strength data
              });

          });
        } else {

          // **For IOS**

          let options = {
            frequency: 1000,
            enableHighAccuracy: false
          };

          this.watch = this.geolocation.watchPosition(options).filter((p: any) => p.code === undefined).subscribe((position: Geoposition) => {
            // loading.dismiss();
            console.log("current location at login" + JSON.stringify(position));

            // Run update inside of Angular's zone
            this.zone.run(() => {
              this.currentLat = position.coords.latitude;
              this.currentLng = position.coords.longitude;
            });

          });
        }

EDIT : First installation is always going fine. But Sometimes you might get errors for no reason in subsequent installations. To make this error (any error with this plugin ) go away.Follow these steps :

1. Remove this plugin from your project (including config.xml and package.json).

2. Delete/Remove android platform.

3. Delete plugins folder.

4. Now reinstall this plugin again, following the steps above.

kumar kundan
  • 2,027
  • 1
  • 27
  • 41
  • I try use that code but i am getting below error: ion-dev.js?v=3.1.11:156 ERROR Error: Uncaught (in promise): ReferenceError: AdvancedGeolocation is not defined ReferenceError: AdvancedGeolocation is not defined Please help to sort out it – Rahul Borole Aug 17 '18 at 06:12
  • try removing and adding this plugin again. Also please check if you have declared `declare var AdvancedGeolocation:any;` on top the component you have written your code. – kumar kundan Aug 20 '18 at 05:23
  • @kumarkundan is got solution this problem? I am facing same problem – Nitin Karale Jan 09 '19 at 15:51
  • @NitinKarale use above answered way – kumar kundan Jan 09 '19 at 18:08
  • what's the problem you are facing @AbhiRam tell me ?? – kumar kundan Mar 06 '19 at 15:48
  • i have n't tested it for ionic4 but i think it should work with little bit changes here and there .. you just have to put in some effort because it's working perfectly for ionic3. I'm bit busy, otherwise i would have made a POC for you. If i got some free time i will post a update for ionic 4. – kumar kundan Mar 06 '19 at 16:48
2

I have gone through the problem and find the solution.

the best way to get geolocation of the user is to use this plugin https://ionicframework.com/docs/native/geolocation/

do not forget to add this is app.moudle.ts as its a provider.

by simply adding this code in app component i was able to get location( do not forget to import and add in constructor)

 this.geolocation.getCurrentPosition({ enableHighAccuracy: true }).then((resp) => {
      console.log(resp);
    }, Error => {
      console.log(Error);
    }).catch(Error => {
      console.log(Error);
    })

i only have the same error while i was using ionic cordova run android --livereload that is insecure origin

but when i use ionic serve i can see the response in browser and also after using ionic cordova run android

just to confirm response in android i check the chrome debugger.

Community
  • 1
  • 1
Anil
  • 986
  • 10
  • 21
  • not working on actual device (android 7).....but it is working fine for ios......i tried on android 7 – kumar kundan Sep 12 '17 at 09:29
  • Can you give two more clarity in this. 1. did you signed the app and tested it . 2. i hope you are not testing it in live reload in actual android 7. i just tested it in android 7 its working fine with the plugin i mentioned in answer – Anil Sep 19 '17 at 08:01
  • 1
    bro it's not working on any android physical device .... not working at all , even after signing it, `this.geolocation.getCurrentPosition()` is not working for android physical device... works well on IOS physical device and also on browser. – kumar kundan Sep 19 '17 at 12:04
  • did you connect the device with computer and checked the console for any errors ?, if yes secure origin is the same error are you getting ? – Anil Sep 19 '17 at 12:52
  • 1
    I have also tried but not working for me.i didn't receive the error callback or not rceived success callback.do you know why? – Kapil Soni Apr 29 '19 at 18:36
0

It works for me

import { Geolocation } from '@ionic-native/geolocation/ngx';
import { NativeGeocoder, NativeGeocoderOptions, NativeGeocoderResult } from '@ionic-native/native-geocoder/ngx';

geoencoderOptions: NativeGeocoderOptions = {
    useLocale: true,
    maxResults: 5
};

constructor(
    private geolocation: Geolocation,
    private nativeGeocoder: NativeGeocoder
) {

    getCurrentLocation() {
        this.geolocation.getCurrentPosition()
            .then((resp) => {

                this.getGeoencoder(resp.coords.latitude, resp.coords.longitude);

            }).catch((error) => {
                console.log('Error getting location', error);
            });
    }

    //geocoder method to fetch address from coordinates passed as arguments
    getGeoencoder(latitude, longitude) {
        this.nativeGeocoder.reverseGeocode(latitude, longitude, this.geoencoderOptions)
            .then((result: NativeGeocoderResult[]) => {

               const address = this.generateAddress(result[0]);

            })
            .catch((error: any) => {
                // alert('Error getting location' + JSON.stringify(error));
            });
    }

    //Return Comma saperated address
    generateAddress(addressObj) {
        let obj = [];
        let address = "";
        for (let key in addressObj) {
            obj.push(addressObj[key]);
        }
        obj.reverse();
        for (let val in obj) {
            if (obj[val].length)
                address += obj[val] + ', ';
        }
        return address.slice(0, -2);
    }
Siddhartha Mukherjee
  • 2,703
  • 2
  • 24
  • 29
-1

you need to provide the permission for Android app as follows:

<feature name="Geolocation">
    <param name="android-package" value="org.apache.cordova.GeoBroker" />
</feature>

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
Krsna Kishore
  • 8,233
  • 4
  • 32
  • 48
  • I already did. it's not working .... i have added various other permission along with these based on other answers from stackoverflow, but still no luck.... – kumar kundan Sep 19 '17 at 09:49
  • @kumarkundan are you getting any console errors? and also try to check with installing `Crosswalk WebView Engine` – Krsna Kishore Sep 19 '17 at 10:01
-1

I ran into a similar problem. When I build from the terminal with the --prod flag, I no longer see this error since it is now requesting position over https.

Built without --prod flag

Built using the --prod flag

Edit: Sorry for the format, I hope that this makes a little more sense. I used the following function in a service that I could call from anywhere to get the latitude, longitude, accuracy, and timestamp. The key though is using the --prod flag in the terminal when building the app.

this.geolocation.getCurrentPosition().then(position => {
     let locationObj = {
            lat: position.coords.latitude,
            lon: position.coords.longitude,
            timestamp: position.timestamp,
            accuracy: position.coords.accuracy
     };
resolve(locationObj);
})
Raksha Saini
  • 604
  • 12
  • 28
Justin B
  • 29
  • 4
  • Thanks and welcome to Stack Overflow. Pls share a snippet from your source code to show which method you called on which object. Also please paste your transcripts here, instead of (or as well as) providing images for your console, to help users search for your answer. – dcorking Jan 30 '18 at 18:04
  • @Justin this is n't going to help you , problem is still there for android physical devices it's not working. – kumar kundan Feb 16 '18 at 05:57
-1

this method is working for bot android and browser

watchLocation() {
    this.watchLocationUpdates = this.geolocation.watchPosition({ maximumAge: 60000, timeout: 25000, enableHighAccuracy: true })
      .subscribe(resp => {
        this.latitude = resp.coords.latitude;
        this.longitude = resp.coords.longitude;
        this.altitude = resp.coords.altitude;
        this.accuracy = resp.coords.accuracy;
        this.altAccuracy = resp.coords.altitudeAccuracy;
        this.heading = resp.coords.heading;
        this.speed = resp.coords.speed;
        this.timestamp = new Date(resp.timestamp);
      });
 }
Asad Riaz
  • 1
  • 2
-2

I found solution for me: use google api https://www.googleapis.com/geolocation/v1/geolocate?key={API_KEY} If platform Android I use google api.

wstudiokiwi
  • 880
  • 1
  • 15
  • 33