Geolocation + Google Maps API

Hello,

I installed Geolocation from native Ionic 2 and Google Maps API via a CDN placed in index.html (last element)

With Ionic serve I get the coordinates from my position and I get the coordinates of the position via a request API. It’s “working”, I calculate distance between this two locations and display how long it takes. First, the request to get my coordinates via Geolocation is very long (2-5sec). Before, with Ionic 1 it was very fast.

But the real problem is when I try to emulate the application with ios-sim, nothing happens.

I also have another problem : when the request is done, i got my coordinates and put them into this.coordinates for example, but on the HTML it doesn’t reload. Well, sometimes it does, but not everytime, don’t ask me why I wouldn’t have the answer. However, I still get the coordinates in the console and in my var, it seems like it’s just the HTML that doesn’t reload itself, except when we click on a UIelement. Thank you for your answers !

  Your system information:
  Cordova CLI: 6.2.0
  Gulp version:  CLI version 3.9.1
  Gulp local:   Local version 3.9.1
  Ionic Framework Version: 2.0.0-beta.10
  Ionic CLI Version: 2.0.0-beta.32
  Ionic App Lib Version: 2.0.0-beta.18
  ios-deploy version: 1.8.6 
  ios-sim version: 5.0.8 
  OS: Mac OS X El Capitan
  Node Version: v6.2.2
  Xcode version: Xcode 7.3.1 Build version 7D1014 
  

 // ERROR ON XCODE LOG WHEN I OPEN THE PAGE
 2016-07-26 15:24:56.409 MyApp[5410:195475] locationManager::didFailWithError (null)
 2016-07-26 15:24:56.479 MyApp[5410:195475] The operation couldn’t be completed. (kCLErrorDomain error 0.)


// MYPAGE.TS
import {Component} from '@angular/core';
import {NavController, NavParams, Platform} from 'ionic-angular';
import {Observable} from 'rxjs/Observable';
import {Http} from '@angular/http';
import {configClient, GeoWatchPos} from '../services/services';
import 'rxjs/add/operator/map';
import {Geolocation} from 'ionic-native';
declare var require: any;
declare var google:any;
var mapboxgl = require('mapbox-gl');


@Component({
  templateUrl: 'build/pages/infrastructure-content/infrastructure-content.html',
  providers: [GeoWatchPos]
})
export class InfrastructureContentPage {
  private menuState:any;
  private infos:any;
  private restInfos:any;
  private baseURL = configClient.baseURL;
  private clientId = configClient.clientId;
  private title:any;
  private pos:any;
  // GOOGLE 
  private APIKeyGoogle = '&key=AIzaSyBh_7Jiie5tHEgTaqvigNoq4__xsEBzmTQ';
  private baseURLGoogle = 'https://maps.googleapis.com/maps/api/geocode/json?address=';
  private distanceResponse:any;
  // GOOGLE DISTANCE
  private modeDistances = ["WALKING", "BICYCLING", "DRIVING"];
  private distances = {
    'WALKING': 0,
    'BICYCLING': 0,
    'DRIVING': 0
  }
  private coordResponse:any;
  // MAPBOX 
  private APIKeyMapbox = '?access_token=pk.eyJ1Ijoic2tyYWZmdCIsImEiOiIzMGQyM2EwYzA3MDMzNDgxMmZkMmExZmQxZDdlYzI3OSJ9.Ya8yCBO0opgps_gvTZ6ObQ';
  private baseURLMapbox = 'https://api.mapbox.com/v4/mapbox.streets/';
  private marker = 'pin-l+48C'
  private mapboxImg:any;
  // GET CURRENT POSITION 
  private coordLongUser:any;
  private coordLatUser:any;

  constructor(private nav: NavController, navParams: NavParams, private http: Http, private platform: Platform, private geowatchpos: GeoWatchPos) {
    this.menuState = navParams.get('menuState') || 'disabled';
    this.infos   = navParams.get('data');
    this.restInfos = navParams.get('restInfos');
    this.title = this.infos.title || navParams.get('parentTitle') || '';
    console.log(this.infos);
    console.log(this.restInfos);
    this.getCoord();
    this.getTestGeoBack();
  }

  // GET COORD FROM ADRRESS TO COORDINATES @GOOGLE GEOCODER
  getCoord() {
    var address = this.baseURLGoogle + this.infos.address + ' ' + this.infos.city + ' ' + this.infos.zip + ' ' + this.APIKeyGoogle;
    console.log(address);
    this.http.get(address).map(res => res.json()).subscribe(data => {
      this.coordResponse = data;
      console.log(this.coordResponse);
      this.getCurrentPosition();
      this.showMap();
    });
  }

  /* A CHANGER AVEC UN GEOLOC WATCH DANS LES SERVICES */
  getCurrentPosition() {    
    var self = this;

    function onSuccess(position) {
        self.coordLongUser =  position.coords.longitude;
        self.coordLatUser =  position.coords.latitude;
        for (var type of self.modeDistances) {
          self.getDistance(type);
        }
        self.geowatchpos.clearWatchPosition();
    }

    function onError(error) {
        console.log(error.code);
        console.log(error.message);
    }
    this.geowatchpos.watchPosition(onSuccess, onError);    
  }

  // GET DISTANCE BETWEEN TWO PLACE @GOOGLE MAP API
  getDistance(type) {
    var self = this;
    var origins = String(this.coordResponse.results[0].geometry.location.lat) + ',' + String(this.coordResponse.results[0].geometry.location.lng);
    var destinations = String(this.coordLatUser) + ',' +  String(this.coordLongUser);
    var distanceService = new google.maps.DistanceMatrixService();
    distanceService.getDistanceMatrix({
        origins: [origins],
        destinations: [destinations],
        travelMode: google.maps.TravelMode[type],
        unitSystem: google.maps.UnitSystem.METRIC,
        durationInTraffic: true,
        avoidHighways: false,
        avoidTolls: false
    },
    function (response, status) {
        if (status !== google.maps.DistanceMatrixStatus.OK) {
            console.log('Error:', status);
        } else {
            console.log(response);
            var distanceType = Math.floor((response.rows[0].elements[0].duration.value) / 60);
            self.distances[type] = distanceType;
        }
    });
  }

  // DISPLAY AN IMAGE TO SHOW THE PLACE @MAPBOX
  showMap() {
    var coords = this.coordResponse.results[0].geometry.location.lng + ',' + this.coordResponse.results[0].geometry.location.lat;
    this.mapboxImg = this.baseURLMapbox + this.marker + '(' + coords + ')' + '/' + coords + ',15' + '/400x200@2x.png' + this.APIKeyMapbox;
  }
}



 // PAGE HTML
<ion-header>
  <ion-navbar no-border-bottom>
    <button *ngIf="menuState == 'enabled'" menuToggle left class="bar-button bar-button-default bar-button-menutoggle bar-button-icon-only" ng-reflect-hidden="false" ng-reflect-menu-toggle>
      <ion-icon name="menu" role="img" class="ion-md-menu" aria-label="menu" ng-reflect-name="menu"></ion-icon>
    </button>
    <ion-title>{{title}}</ion-title>
  </ion-navbar>
</ion-header>


<ion-content class="infrastructure-content">
  <div class="container-img" style="background: url('https://unsplash.it/1280/720/?random');"></div>
  <div class="container" padding>
    <h4>
      {{infos.name}}
    </h4>
    <div class="container-button">
      <button class="btn" (click)="launch()" *ngIf="infos.address" full custom>
        <span></span>
        <span textColor>{{infos.address}}</span>
      </button>
      <button (click)="launch(infos.phone)" class="btn" *ngIf="infos.phone" full custom>
        <span></span>
        <span textColor>{{infos.phone}}</span>
      </button>
      <button (click)="launch(infos.fax)" class="btn" *ngIf="infos.fax" full custom>
        <span></span>
        <span textColor>{{infos.fax}}</span>
      </button>
      <button (click)="launch(infos.address)" class="btn" *ngIf="infos.email" full custom>
        <span></span>
        <span textColor>{{infos.email}}</span>
      </button>
      <button (click)="launch(infos.web)" class="btn" *ngIf="infos.web" full custom>
        <span></span>
        <span textColor>{{infos.web}}</span>
      </button>
    </div>
    <p [innerHTML]="infos.details" *ngIf="infos.details"></p>
    <p [innerHTML]="infos.horaires" *ngIf="infos.horaires"></p>
    <div>
      <button>{{distances.WALKING}} mn</button>
      <button>{{distances.BICYCLING}} mn</button>
      <button>{{distances.DRIVING}} mn</button>
    </div>
    <img *ngIf="mapboxImg" src="{{mapboxImg}}" alt="batiment">
  </div>
</ion-content>