Reputation: 71
Newbie in Angular and web programming. However using whatever I have learnt I created an Angular2 component using Google Map APIs and it is routing between two points, however I want to use Observable instead of plain function which gets fired upon response from API. Any help will be highly appreciated. Here is my code:
import { Component, OnInit, OnChanges } from '@angular/core';
declare var google: any;
@Component({
selector: 'gmap',
templateUrl: 'gmap.component.html',
styleUrls: ['gmap.component.css']
})
export class GMapComponent implements OnInit, OnChanges {
directionsService = new google.maps.DirectionsService();
directionsDisplay;
map;
ngOnInit() {
this.directionsDisplay = new google.maps.DirectionsRenderer();
this.map = new google.maps.Map(document.getElementById('gmap'), {
zoom: 8,
center: { lat: 51.59, lng: -0.44 }
});
this.directionsDisplay.setMap(this.map);
}
onSearchBarGO($event) {
var directionsDisplay = this.directionsDisplay;
//console.log($event);
this.directionsService.route({
origin: $event.from,
destination: $event.to,
waypoints: [],
optimizeWaypoints: true,
travelMode: $event.mode.toUpperCase()
}, function (response, status) {
var parent = this;
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
}
Upvotes: 2
Views: 766
Reputation: 3560
You have to use Observable's conversion factory methods.
Observable.bindCallback(this.directionsService.route)({
origin: $event.from,
destination: $event.to,
waypoints: [],
optimizeWaypoints: true,
travelMode: $event.mode.toUpperCase()
})
.subscribe( function (response, status) {
var parent = this;
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
Upvotes: 1