Search code examples
cordovaionic2geolocation

Ionic 2 - Geolocation timeout error


I want to detect latitude and longitude everytime when I click on button. I have tried to search on many sites and blogs but not getting any specific solution. I have also installed cordova-plugin-geolocation and used like this:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, Platform } from 'ionic-angular';
import {Camera, CameraOptions} from '@ionic-native/camera';
import { Geolocation, Geoposition } from '@ionic-native/geolocation';

constructor(public navCtrl: NavController, public navParams: NavParams, private camera : Camera, 
    public geolocation: Geolocation, public platform: Platform) {
  }

capturePhotos()
{
    let GPSoptions = {timeout: 10000, enableHighAccuracy: true, maximumAge: 3600};
      this.geolocation.getCurrentPosition(GPSoptions).then((position) => {

        console.log("IN");

        console.log(position.coords.latitude);
        console.log(position.coords.longitude);

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

After getting timeout error I increased the timeout to 50000 but no success. Above capturephoto function will be called as below:

<ion-navbar hideBackButton side="left">
      <ion-title style="margin-left: 0px;">
          <div>
              <ion-icon ios="ios-add" md="md-add" class="menuIcon" (click)="capturePhotos()"></ion-icon><span class="menuTitle">My Photos</span>
          </div>
      </ion-title>  
  </ion-navbar>

When I try to run it in android emulator it will fetch Lat Long when I first time click on add icon but when I click on second or more time it stops working and throws the error: PositionError {} code: 3 message: "Timeout expired"


Solution

  • I resolved this issue by doing the following changes:

    1) I set my location mode to High accuracy in my phone settings.

    2) After that I changed the code from "this.geolocation" to "navigator.geolocation".

    3) There was some issue in my code with Callbacks. When detecting for lat lon I was calling another function and in that I was redirecting to the new page. So solved this callback issue and after that I'm now getting lat lon values successfully every time I click on button.