Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

carolina

Geolocalização Google Maps

Recommended Posts

Prezados, bom dia!

 

Há alguns dias estou testando a rotina abaixo para pegar a localização do dispositivo e mostrar a distância e o tempo até um determinado endereço. O código estava funcionando perfeitamente pelo computador ou por smartphone. Há uns 3 dias verifiquei que o Google Chrome não está mais conseguindo localizar a posição atual do dispositivo via smartphone. O Google Chrome não está nem perguntando se deseja permitir a minha localização. Já testei em outros navegadores e está funcionando perfeitamente.

 

Alguém sabe o que pode ser? Será que é algum bug do Chrome?

 

Desde já agradeço qualquer ajuda.

 

 

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Traçar Rota</title>
<script>
var map, geocoder;
var mapDisplay, directionsService;
function success(position) {
//cityByLatLng(position.coords.latitude, position.coords.longitude);
var s = document.querySelector('#status');
if (s.className == 'success') {
return;
}
s.innerHTML = "found you!";
s.className = 'success';
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcanvas';
mapcanvas.style.height = '400px';
mapcanvas.style.width = '560px';
document.querySelector('article').appendChild(mapcanvas);
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeControl: false,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"You are here!"
});
var address2 = 'Rua Conde de Bonfim, 1033 - Tijuca, Rio de Janeiro - RJ, Brasil';
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address2}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
//map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
//icon: image,
position: results[0].geometry.location
});
//infowindow.open(map,marker);
/*
google.maps.event.addListener(marker, 'click', function()
{
infowindow.open(map,marker);
});
*/
//alert(document.getElementById('endereco').value);
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
geocoder.geocode({'location': latlng}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
document.getElementById('endereco').innerHTML = results[0].formatted_address;
mostrarRota(results[0].formatted_address, address2);
CalculaDistancia(results[0].formatted_address, address2);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
else
{
alert("Geocode não foi bem sucedida pelo seguinte motivo: " + status);
}
});
}
function initializeDirections () {
directionsService = new google.maps.DirectionsService();
mapDisplay = new google.maps.DirectionsRenderer();
mapDisplay.setMap(map);
mapDisplay.setPanel(document.getElementById("panel"));
}
function mostrarRota(endInicial, endFinal)
{
document.getElementById('panel').innerHTML = '';
initializeDirections ();
var endDe = endInicial;
var endPara = endFinal;
var request = {
origin:endDe,
destination:endPara,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
mapDisplay.setDirections(response);
}
else
{
alert("Não foi encontrado uma geolocalização válida para este endereço.");
}
});
}
function cityByLatLng(latitude, longitude) {
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);
geocoder.geocode({'location': latlng}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
document.getElementById('endereco').innerHTML = results[0].formatted_address;
return results[0].formatted_address;
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
function error(msg) {
var s = document.querySelector('#status');
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
// console.log(arguments);
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
error('not supported');
}
function CalculaDistancia(inicio, fim) {
document.getElementById('litResultado').innerHTML = 'Aguarde...';
//Instanciar o DistanceMatrixService
var service = new google.maps.DistanceMatrixService();
//executar o DistanceMatrixService
service.getDistanceMatrix(
{
//Origem
origins: [inicio],
//Destino
destinations: [fim],
//Modo (DRIVING | WALKING | BICYCLING)
travelMode: google.maps.TravelMode.DRIVING,
//Sistema de medida (METRIC | IMPERIAL)
unitSystem: google.maps.UnitSystem.METRIC
//Vai chamar o callback
}, callback);
}
//Tratar o retorno do DistanceMatrixService
function callback(response, status) {
//Verificar o Status
if (status != google.maps.DistanceMatrixStatus.OK)
//Se o status não for "OK"
document.getElementById('litResultado').innerHTML = status;
else {
//Se o status for OK
//Endereço de origem = response.originAddresses
//Endereço de destino = response.destinationAddresses
//Distância = response.rows[0].elements[0].distance.text
//Duração = response.rows[0].elements[0].duration.text
document.getElementById('litResultado').innerHTML = "<strong>Origem</strong>: " + response.originAddresses +
"<br /><strong>Destino:</strong> " + response.destinationAddresses +
"<br /><strong>Distância</strong>: " + response.rows[0].elements[0].distance.text +
" <br /><strong>Duração</strong>: " + response.rows[0].elements[0].duration.text;
//Atualizar o mapa
//$("#map").attr("src", "https://maps.google.com/maps?saddr=" + response.originAddresses + "&daddr=" + response.destinationAddresses + "&output=embed");
}
}
</script>
</head>
<body>
<article>
<p><span id="status">Please wait whilst we try to locate you...</span></p>
</article>
<br /><br />
Endereço
<div id="endereco"></div>
<br style="clear: both;" /><div id="litResultado" style="clear: both;"></div>
<br style="clear: both;" /><div id="panel" style="clear: both; float: left; margin-top: 10px; width:65%;"></div>
</section>
</body>
</html>

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.