Nicolás Marzano
Nicolás Marzano

Reputation: 161

Google Maps not working with Ionic2 on Android

I'm making a mobile app mostly following the examples in Ionic's doc pages. The aim is to get the user's latitude and longitude using android's Geolocation service, and display the position using the Google Maps service.

The Geolocation service works as intended and when given access to the device's location the latitude and longitude display on the application correctly and update every few seconds.

The Google Maps service is what I can't get working: I get only a light grey square and never any kind of update. The relevant code in question:

geo.ts:

import { Component, OnInit, ViewChild } from '@angular/core';
import { NavController } from 'ionic-angular';

import { Geolocation } from '@ionic-native/geolocation';
import {
 GoogleMaps,
 GoogleMap,
 GoogleMapsEvent,
 GoogleMapOptions,
 CameraPosition,
 MarkerOptions,
 Marker
} from '@ionic-native/google-maps';

@Component({
  selector: 'geo-contact',
  templateUrl: 'geo.html'
})
export class GeoPage implements OnInit {

  private watch;
  private lat=0;
  private lng=0;
  private map: GoogleMap;
  private mapReady=false;

  @ViewChild('mapCanvas') mapCanvas;

  constructor(public navCtrl: NavController, private geolocation: Geolocation) {

  }

  ngOnInit() {
    this.watch = this.geolocation.watchPosition();
    this.watch.subscribe((data)=>{
        this.lat=data.coords.latitude;
        this.lng=data.coords.longitude;
        console.log('map ready? '+this.mapReady);
        if(this.mapReady){
            console.log('updating map position');
            this.map.moveCamera({
                target: {
                    lat: this.lat,
                    lon: this.lng
                },
                zoom: 8,
                tilt: 0
            });
        }
    });
  }

  ionViewDidLoad(){
    console.log('ionViewDidLoad');
    this.loadMap();
  }

  loadMap(){
    let mapOptions: GoogleMapOptions = {
        camera: {
            target: {
                lat: this.lat,
                lon: this.lng
            },
            zoom: 8,
            tilt: 0
        },
        'mapType': 'MAP_TYPE_NORMAL'
    };

    this.map = GoogleMaps.create(this.mapCanvas.nativeElement, mapOptions);

    console.log('GoogleMaps.create called, waiting for GoogleMapsEvent.MAP_READY');

    this.map.one(GoogleMapsEvent.MAP_READY)
            .then(()=>{
                console.log('GoogleMapsEvent.MAP_READY fired');
                this.mapReady=true;
                this.map.addMarker({
                    title: 'You\'re Here',
                    icon: 'blue',
                    animation: 'DROP',
                    position: {
                        lat: this.lat,
                        lng: this.lng
                    }
                })
                .then(marker => {
                    marker.on(GoogleMapsEvent.MARKER_CLICK)
                        .subscribe(()=>{
                            alert('clicked');
                        });
                });
            });

    this.map.one(GoogleMapsEvent.MAP_LOADED)
            .then(()=>{
                console.log('GoogleMapsEvent.MAP_LOADED fired');
            });
  }
}

geo.html:

<ion-header>
  <div id="pre-navbar" style="display: inline-block;"><img src="./assets/imgs/logo-educacion.svg" style="height:40px;"></div>
  <ion-navbar color="primary">
    <ion-title>
      Maps
    </ion-title>
  </ion-navbar>
</ion-header>
<ion-content>
  <div *ngIf="lat!=0 && lng!=0">
    <ion-list>
      <ion-item>LATITUDE: {{lat}}</ion-item>
      <ion-item>LONGITUDE: {{lng}}</ion-item>
    </ion-list>
  </div>
  <div *ngIf="lat==0 || lng==0">
    <img src="./assets/imgs/Spinner-1s-200px.gif" style="height:40px;display:block;margin-left:auto;margin-right:auto;margin-top:20px;">
  </div>
  <div style="position:absolute;width:100%;height:100%;" padding>
    <div #mapCanvas data-tap-disabled="true" style="min-width: 200px; min-height: 200px; height:80%;"></div>
  </div>
</ion-content>

As you can see I've added output to the console to log the state of mapReady which only changes to true once GoogleMapsEvent.MAP_READY has fired, and this is the output I get after a while, indicating it never does fire (the 'fetched quote' logs belong to a different view's functionality):

js console output

Small changes to the example code were made following different solutions like the use of @ViewChild and some juggling with the element's height property, but all I could do was get from nothing displaying to the light grey box. I'd really appreciate help with getting the Maps service to display properly.

Screen output:

screen output showing the grey box

EDIT 1:

I'm using Cordova 8.0.0 and running the app on mobile, debugging via chrome://inspect.

Upvotes: 1

Views: 763

Answers (2)

Wouter
Wouter

Reputation: 790

First a few checks:

  1. Are you running in the browser or on a device / simulator? Because the GoogleMaps native plugin is only compatible with iOS and Android, not with the browser. In case your app has to work in the browser as well, have a look at the Google Maps Javascript SDK. A few good tutorials can be found here: https://www.joshmorony.com/ionic-2-how-to-use-google-maps-geolocation-video-tutorial/

  2. Next run ionic info and check if you have the latest version of Cordova (currently 8.0.0). If not install or upgrade it. The current Google Maps Cordova plugin requires 7.1 or higher.

  3. Then follow the instructions to install the Cordova plugin on: https://ionicframework.com/docs/native/google-maps/

  4. In your code make sure to call loadMap() only when the platform is ready.

  5. Note that there's currently a problem loading Cordova plugins when using live reload in Ionic. See: https://github.com/ionic-team/ionic-app-scripts/issues/1354

A minimal working example is:

import { Component, ViewChild } from '@angular/core';
import { Platform } from 'ionic-angular';
import { GoogleMaps, GoogleMap, GoogleMapsEvent} from '@ionic-native/google-maps';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  private map: GoogleMap;

  @ViewChild('mapCanvas') mapCanvas;

  constructor(private platform: Platform) {
    this.platform.ready().then(() => {
      this.loadMap();
    });
  }

  loadMap() {
    this.map = GoogleMaps.create(this.mapCanvas.nativeElement);
    this.map.one(GoogleMapsEvent.MAP_READY)
      .then(() => { console.log("Map ready"); });
  }
}

Upvotes: 1

wf9a5m75
wf9a5m75

Reputation: 6158

Blank map is always api key problem. https://github.com/mapsplugin/cordova-plugin-googlemaps-doc/blob/master/v1.4.0/TroubleShooting/Blank-Map/README.md

Check your all setting, or try new api keys.

Upvotes: 0

Related Questions