Google geolocation works on the pc browser, but not on the android browser

Asked

Viewed 897 times

0

Using Ruby, Sinatra, Slim, Javascript, Google maps v3 API. Geolocation works perfectly in the browser on the PC, the map is generated with the partner marker, when you click on the button you are asked to geolocate the browser, create a new marker at that position and generate the route. Put in browser on android when click on button falls on error:

infoWindow.setContent(browserHasGeolocation ?
'Erro: O serviço de geolocalização falhou.'

In my KEY API I enabled everything related to MAPS and ANDROID.

I made a Fiddle, and it works on android, only it is without API KEY.

Fiddle

EDIT 1: I found that google only allows you to use getCurrentPosition() on HTTPS://connections (it would never work by accessing my local IP), in Heroku it only works if I use https:// before the address in both the PC browser and the android browser.

<button id="rota">Rota até o parceiro.</button>
<div id="map"></div>

<script async defer src="https://maps.googleapis.com/maps/api/js?key=#{ENV['GOOGLE_API_KEY']}&callback=initMap"></script>

<script>
  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
  function initMap() {
    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 for the following reason: ' + status);
      }
    });
  }

  // Função que gera rota
  function calculateAndDisplayRoute(directionsService, directionsDisplay, pos) {
    directionsService.route({
      origin: pos,
      destination: 'Fortaleza - CE',
      // Note that Javascript allows us to access the constant
      // using square brackets and a string value as its
      // "property."
      travelMode: google.maps.TravelMode['DRIVING']
    }, function(response, status) {
      if (status == 'OK') {
        directionsDisplay.setDirections(response);
      } else {
        window.alert('Directions request failed due to ' + status);
      }
    });
  }
</script>
<style>
  /* Always set the map height explicitly to define the size of the div
  * element that contains the map. */
  #map {
    height: 300px;
  }
</style>

1 answer

0


  • If this is the solution, mark the answer as accepted.

  • I can’t, the answer was myself. I can only mark as correct after two days.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.