Skip to content

Instantly share code, notes, and snippets.

@0x62
Last active June 17, 2021 18:30
Show Gist options
  • Save 0x62/ed569617a5c36d307d13ed8169290042 to your computer and use it in GitHub Desktop.
Save 0x62/ed569617a5c36d307d13ed8169290042 to your computer and use it in GitHub Desktop.
import { GoogleMapsAPIWrapper } from '@agm/core';
import { Directive, Output, EventEmitter } from '@angular/core';
declare var google: any;
@Directive({
selector: 'agm-location-marker'
})
export class AgmLocationMarker {
marker: any;
map: any;
@Output('positionChanged') change: EventEmitter<any> = new EventEmitter();
constructor (private gmapsApi: GoogleMapsAPIWrapper) {}
ngOnInit(){
this.gmapsApi.getNativeMap().then(map => {
if (!navigator.geolocation) return;
this.map = map;
navigator.geolocation.watchPosition(this.onPositionUpdate.bind(this), function(err) {
console.log('Unable to get location:', err)
}, {
enableHighAccuracy: true,
maximumAge: 1000
})
});
}
onPositionUpdate(position) {
let pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
}
// Emit position change event
this.change.emit(pos)
if (this.marker) {
// Update marker position
this.marker.setPosition(pos)
return;
}
// Marker needs to be created
this.marker = new google.maps.Marker({
map: this.map,
position: pos
})
this.map.setCenter(this.marker.getPosition())
}
}
<agm-map [latitude]="lat" [longitude]="lng" [zoom]="13">
<agm-location-marker (positionChanged)="positionChanged($event)"></agm-location-marker>
</agm-map>
positionChanged(pos) {
// pos = { lat: 1, lng: 1 };
}
@dalepo
Copy link

dalepo commented May 7, 2020

Great directive.
I'd recommend to release resources on OnDestroy since watchPosition might execute even when this directive is destroyed.

   watchId: number;
   ngOnInit(): void {
        ....
        // Save watchId
        this.watchId = navigator.geolocation.watchPosition(this.onPositionUpdate.bind(this), (err: PositionError) ...
       ....
  }
  
  ngOnDestroy(): void {
    // Release resources
    if (navigator.geolocation && this.watchId) {
      navigator.geolocation.clearWatch(this.watchId);
    }
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment