Reputation:
I have an Ionic 3 app, using Google Maps. On load I am rendering a map with a Marker on the current user's location.
I am using watchPostion to update the marker when the user's position changes.
However, the marker keeps being set, even if the position does not change, it is added on top.
Also, when the position does change, the marker does not move, rather a new one is added, so I end up with a trail of markers.
I'd like to only add the maker if the position has changed and either remove / add the marker if it does, or simply have it's position updated.
This is my Ionic Component / Page -
import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
import { MapStyle } from './map-style';
declare var google;
@Component({
selector: 'home-page',
templateUrl: 'home.html'
})
export class HomePage {
@ViewChild('map') mapElement: ElementRef;
map: any;
constructor(
public navCtrl: NavController,
public geolocation: Geolocation
) { }
ionViewDidEnter() {
this.initializeMap();
}
private initializeMap() {
const mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
rotateControl: false,
fullscreenControl: false,
styles: [...MapStyle]
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
this.geolocation.watchPosition()
.subscribe((position) => {
const geolocate = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
const currentUserMarker = new google.maps.Marker({
map: this.map,
position: geolocate,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 8.5,
fillColor: "#2a929f",
fillOpacity: 0.4,
strokeWeight: 0.4
}
// content: `${position.coords.latitude} <br /> ${position.coords.longitude}`
});
this.map.panTo(geolocate);
currentUserMarker.setPosition(geolocate);
}, (err) => this.handleError)
}
private handleError(err) {
console.log(err);
}
}
Upvotes: 0
Views: 949
Reputation:
Rookie mistake.
Every time watchPosition was called I created a new instance of the marker.
Declared marker higher in the scope and then wrapped my logic in an if / else.
if (this.marker != null) {
this.marker.setPosition(geolocate);
this.map.panTo(geolocate);
} else {
this.marker = new google.maps.Marker({
position: geolocate,
map: this.map,
............
Upvotes: 1