Last active
June 17, 2021 18:30
-
-
Save 0x62/ed569617a5c36d307d13ed8169290042 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<agm-map [latitude]="lat" [longitude]="lng" [zoom]="13"> | |
<agm-location-marker (positionChanged)="positionChanged($event)"></agm-location-marker> | |
</agm-map> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
positionChanged(pos) { | |
// pos = { lat: 1, lng: 1 }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great directive.
I'd recommend to release resources on OnDestroy since watchPosition might execute even when this directive is destroyed.