Skip to content

Instantly share code, notes, and snippets.

@ca0v
Created March 4, 2015 20:18
Show Gist options
  • Save ca0v/35c8f70c367873baa04d to your computer and use it in GitHub Desktop.
Save ca0v/35c8f70c367873baa04d to your computer and use it in GitHub Desktop.
Use Google Directions to render a route on a Google Map
import Deferred = require("dojo/Deferred");
class Navigation {
private _directions: google.maps.DirectionsResult;
private _ready: Deferred<Navigation>;
constructor(args: {
start?: any;
end?: any;
waypoints?: google.maps.Point[];
}) {
var service = new google.maps.DirectionsService();
this._ready = new Deferred<Navigation>();
var request = <google.maps.DirectionsRequest>{};
request.avoidHighways = false;
request.avoidTolls = false;
request.optimizeWaypoints = true;
request.provideRouteAlternatives = false;
request.region = "us";
request.travelMode = google.maps.TravelMode.DRIVING;
request.unitSystem = google.maps.UnitSystem.IMPERIAL;
if (args.waypoints) {
request.waypoints = args.waypoints.map(w => {
return {
location: w,
stopover: false
};
});
}
request.transitOptions = {
arrivalTime: new Date(),
departureTime: new Date()
};
request.origin = args.start;
request.destination = args.end;
service.route(request,(result, status) => {
switch (status) {
case google.maps.DirectionsStatus.INVALID_REQUEST:
break;
case google.maps.DirectionsStatus.OK:
this._directions = result;
this._ready.resolve(this);
break;
default:
break;
}
});
}
get then() {
return this._ready.then;
}
render(map: google.maps.Map) {
var options = <google.maps.DirectionsRendererOptions>{};
options.map = map;
options.directions = this._directions;
var renderer = new google.maps.DirectionsRenderer(options);
this._ready.then(() => {
renderer.setDirections(this._directions);
});
// how to clear the directions?
}
}
var map = new google.maps.Map(document.getElementById("map-canvas"), {
});
var directions = new Navigation({
start: "Chicago, IL",
end: "St Louis, MO"
});
directions.then(function () {
directions.render(map);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment