I am using angular google maps in my angular 4 application. I am trying to get directions from a point to another point using directive.
Here is directive source code,
import { Directive, Input, OnInit } from '@angular/core';
import {GoogleMapsAPIWrapper} from '@agm/core';
declare let google: any;
@Directive({
selector: '[appDirection]'
})
export class DirectionDirective implements OnInit {
@Input() org;
@Input() dst;
constructor(private gmApi: GoogleMapsAPIWrapper) { }
ngOnInit() {
console.log(' In directive ');
this.gmApi.getNativeMap().then(map => {
const directionsService = new google.maps.DirectionsService;
const directionsDisplay = new google.maps.DirectionsRenderer;
directionsDisplay.setMap(map);
directionsService.route({
origin: {lat: this.org.latitude, lng: this.org.longitude},
destination: {lat: this.dst.latitude, lng: this.dst.longitude},
waypoints: [],
optimizeWaypoints: true,
travelMode: 'TRANSIT'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
});
}
}
And I have added this in app.module.ts under declarations array. I am using this directive in another component, inside component I am defining org and dst as follows,
showDirections( ) {
const dst = {longitude: this.point.longitude, latitude: this.point.latitude};
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
const org = { latitude: position.coords.latitude, longitude: position.coords.longitude};
console.log('Src ' + org.latitude );
});
}
console.log('Dst' + dst.latitude );
}
I am calling above function on a user clicking a button.
The HTML for the component is as follows,
<agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom" appDirection [org]="org" [dst]="dst">
<agm-marker [style.height.px]="map.offsetHeight" [latitude]="lat" [longitude]="lng"></agm-marker>
</agm-map>
I am applying directive as an attribute to agm-map.
When I click on the button which sets org and dst, then direction should display on agm-map. But no directions is currently displaying. Please correct me, where I am wrong. Thanks in advance.
Now I am getting the error as follows,
TypeError: Cannot read property 'latitude' of undefined
org and dst are undefined in directive, but they are set in component.