Last active
August 29, 2015 14:26
-
-
Save mtigdemir/3730d0c3572a551630f1 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
(function(global) { | |
var google = global.google; | |
var directionsService = new google.maps.DirectionsService(); | |
var directionsDisplay; | |
// initialize google map | |
var initialize = function() { | |
var mapOptions = { | |
center: new google.maps.LatLng(-34.397, 150.644), | |
zoom: 5, | |
mapTypeId: google.maps.MapTypeId.ROADMAP | |
}; | |
// initialize map | |
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); | |
directionsDisplay = new google.maps.DirectionsRenderer(); | |
directionsDisplay.setMap(map); | |
// add event on map click | |
// @param {Object} event The custom map event object | |
// which contain latitude and langitude | |
google.maps.event.addListener(map, 'click', function(event) { | |
// getUserPosition is async function | |
// because it require user permission | |
getUserPosition(calcRoute.bind(global, event.latLng)); | |
}); | |
}; | |
// html 5 geolocation API | |
// Get user position | |
var getUserPosition = function(callback) { | |
global.navigator.geolocation.getCurrentPosition(function(position) { | |
var latitude = position.coords.latitude; | |
var langitude = position.coords.longitude; | |
// convert user position to google.maps | |
// LatLng object | |
var origin = new google.maps.LatLng(latitude, langitude); | |
callback(origin); | |
} /*, onError */ ); | |
}; | |
// calc direction from user location | |
// to position clicked on map | |
var calcRoute = function(distPosition, originPosition) { | |
var request = { | |
origin: originPosition, | |
destination: distPosition, | |
travelMode: google.maps.TravelMode.DRIVING // it's work onliy for one continent | |
}; | |
directionsService.route(request, function(result, status) { | |
if (status === google.maps.DirectionsStatus.OK) { | |
directionsDisplay.setDirections(result); | |
} | |
}); | |
}; | |
// events | |
google.maps.event.addDomListener(window, 'load', initialize); | |
}(this)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment