Ionic 2 Geolocation sets a different location when a position is unavailable

    Geolocation.getCurrentPosition().then((position) => {

      let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
      //let latLng = new google.maps.LatLng(40.987469, 29.027119);

      let mapOptions = {
        center: latLng,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
    }).catch((error) => {
        console.log('Error getting location', error);

    });

I am trying to check if a user's position is available or not. When custom gps is open, the code above works. But I need to check if GPS is open, and I will set the place myself when I can’t get the user's location. How to check if a user's location is available or not? I use ion-native geolocation. Thanks in advance.

+3
source share
3 answers

You can use the Diagnosticcordova plugin .

Diagnostic.isLocationEnabled().then( (avail) => {
  console.log(avail);
  if(!avail){
    return Diagnostic.switchToLocationSettings();
  }
}).catch( (err) => {
  console.log(err);
}).then( () => {
  console.log('entered');
  return this.getLocation().then(()=>{ //get location } )

  })
+1
source

, . . :

    if (navigator.geolocation) {
        var options = {
            timeout: 10000,
            enableHighAccuracy: false
        };

        navigator.geolocation.getCurrentPosition(position=> {
            console.info('Position : ' + JSON.stringify(position));

        }, error => {
            console.log(' Error : ' + JSON.stringify(error));
        }, options);
    } else {
         // you can set your custom position here if not location found.
    }
+1

You need to go optionsup Geolocation.getCurrentPosition()to throwcatch

try it

let optionsGPS = {timeout: 4000, enableHighAccuracy: true};
Geolocation.getCurrentPosition(optionsGPS).then((result) => {
  this.loadMap(result.coords.latitude, result.coords.longitude);
}).catch((err) => {
    let alert = this.alertCtrl.create({
        title: 'Error on GPS',
        subTitle: err,
        buttons: 'OK'
    });
    alert.present();
});

I had the same problem and it worked for me

0
source

Source: https://habr.com/ru/post/1677166/


All Articles