Skip to content

Instantly share code, notes, and snippets.

@renesansz
Created November 17, 2015 01:46
Show Gist options
  • Save renesansz/ca5ddb70890252f8aec1 to your computer and use it in GitHub Desktop.
Save renesansz/ca5ddb70890252f8aec1 to your computer and use it in GitHub Desktop.
Angular Gmaps Directions service.
/**
* Initialize Directions Service
*
* @param {Object} origin - The latitude & longitude of origin point
*/
function _InitializeGmapsDirections(origin) {
// Set map zoom base on markers
var _SetMapZoom = function (positionList) {
var bounds = new google.maps.LatLngBounds();
var map = vm.gmaps.control.getGMap();
for (var i = 0, limit = positionList.length; i < limit; ++i) {
bounds.extend(new google.maps.LatLng(positionList[i].latitude, positionList[i].longitude));
}
// Fit the markers on the map.
map.fitBounds(bounds);
};
var destination = angular.copy(vm.branch.Location);
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setOptions({ suppressMarkers: true });
directionsDisplay.setMap(vm.gmaps.control.getGMap());
var request = {
origin: origin.latitude + ',' + origin.longitude,
destination: destination.latitude + ',' + destination.longitude,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC
};
direction = {
saddr: request.origin,
daddr: request.destination
};
// Request direction in Gmaps API
directionsService.route(request, function (response, status) {
console.log('Done');
// If a route is found then render on map.
// Else, display hearing centre on map.
if (status === google.maps.DirectionsStatus.OK) {
_SetMarker(origin, 'origin');
_SetMarker(destination, 'destination');
directionsDisplay.setDirections(response);
_SetMapZoom([origin, destination]);
} else {
console.info('No direction(s) found for this location.');
_SetMarker(vm.branch.Location, 'destination');
}
});
vm.isMapRendered = true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment