Skip to content

Instantly share code, notes, and snippets.

@meritt
Created April 18, 2011 10:19
Show Gist options
  • Save meritt/925111 to your computer and use it in GitHub Desktop.
Save meritt/925111 to your computer and use it in GitHub Desktop.
Google Maps + Geolocation + Маршруты
if (navigator.geolocation) {
// #showroute это id кнопки/ссылки на сайте, нажимая которую мы должны проложить маршрут
var showroute = document.getElementById('showroute');
showroute.addEventListener('click', function(event) {
event.preventDefaults();
// пока строится маршрут не разрешаем нажимать на кнопку/ссылку снова
if (!showroute.classList.contains('disabled')) {
showroute.classList.add('disabled');
navigator.geolocation.getCurrentPosition(function(position) {
// отправляем текущую позицию в функцию для прокладывания маршрута
showRouteService(position);
});
}
}, false);
}
var map = new google.maps.Map(...);
var service = new google.maps.DirectionsService();
var direction = new google.maps.DirectionsRenderer({map: map});
var baloon = new google.maps.InfoWindow();
function showRouteService(position) {
var request = {
origin: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
destination: new google.maps.LatLng(/* координаты офиса */),
travelMode: google.maps.DirectionsTravelMode.WALKING // если в вашем городе работают автомобильные маршруты, можно использовать их
};
// Отправляем запрос на прокладку маршрута
service.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
direction.setDirections(response);
// получаем первый вариант маршрута
var route = response.routes[0].legs[0];
// проставляем маркеры по всему маршруту с описанием изменения маршрута
for (var i=0,length=route.steps.length; i<length; i++) {
var marker = new google.maps.Marker({
position: route.steps[i].start_point,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
balloon.setContent(route.steps[i].instructions);
balloon.open(map, marker);
});
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment