I've been following this helpful tutorial - https://www.joshmorony.com/ionic-2-how-to-use-google-maps-geolocation-video-tutorial/.
Everything works great. However, this example prompts the user to add a marker to the google map by clicking on a button. I want the marker to be automatically added after the map loads in the view.
However, I'm receiving the error cannot read propery of getCentre of undefined
I'm quite sure that is telling me that it is attempting to add the marker before the map is loaded. Below is the code in my page TypeScript file:
import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController } from 'ionic-angular';
import * as $ from "jquery";
import Shuffle from 'shufflejs';
import { Geolocation } from '@ionic-native/geolocation';
declare var google;
@Component({
selector: 'page-locator',
templateUrl: 'locator.html'
})
export class LocatorPage {
@ViewChild('map') mapElement: ElementRef;
map: any;
constructor(public navCtrl: NavController, public geolocation: Geolocation) {
}
ionViewDidLoad() {
// Load the google map
this.loadMap();
}
// Function to add marker at current location
addMarker(){
let marker = new google.maps.Marker({
map: this.map,
animation: google.maps.Animation.DROP,
position: this.map.getCenter()
});
let content = "<h4>Information!</h4>";
this.addInfoWindow(marker, content);
}
addInfoWindow(marker, content){
let infoWindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click', () => {
infoWindow.open(this.map, marker);
});
}
// Function for loading the google map and getting geolocation coords
loadMap(){
this.geolocation.getCurrentPosition().then((position) => {
let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
}, (err) => {
console.log(err);
});
//automatically place marker at current location
this.addMarker();
}
}
Does anyone have a solution for this? Like a trigger that fires after the map has finished loading? I can't seem to find an Ionic lifecycle event that I can run a hook from. Note that I am trying to run the this.addMarker() function after loadMap() has completed