Geolocation with rote
Geolocalização com rotas no click do botão.
HTML
<script src="https://maps.googleapis.com/maps/api/js?v=3&amp;sensor=false"></script>
<button id='rota'>
Rota até o parceiro.</button>
<!-- div onde será gerado o mapa do google -->
<div id='map'></div>
CSS
#map {
height: 300px;
}
JavaScript
var map;
var pos;
//Pega o click no botão
document.getElementById("rota").onclick = function() {
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
directionsDisplay.setMap(map);
var infoWindow = new google.maps.InfoWindow({
map: map
});
// solicita ao browser a localização
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Você está aqui.');
map.setCenter(pos);
//Gera a rota
calculateAndDisplayRoute(directionsService, directionsDisplay, pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Erro: O serviço de geolocalização falhou.' :
'Erro: O seu navegador não suporta geolocalização.');
}
//Primeira função chamada quando o mapa é gerado
map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: {
lat: -3.7913486,
lng: -38.589312
}
});
var geocoder = new google.maps.Geocoder();
geocodeAddress(geocoder, map);
//Cria o marcador para o @endereco do parceiro
function geocodeAddress(geocoder, resultsMap) {
var address = 'Fortaleza - CE';
geocoder.geocode({
'address': address
}, function(results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful...