Insert button to reach a map

Asked

Viewed 2,376 times

0

  • 1

    Vicius Soares, all good? Can you specify your problem better? What have you tried so far? Putting the code can help people answer your question.

  • Hey, Asura, you okay? I need the site to do what the Gmaps app does on mobile: qd vc accesses the app it picks up your location and asks you to put the address where you want to go. Then it plots a route. In the case of the site the destination will already be chosen, I need to pick the customer’s location to create the route.

2 answers

1

If you use HTML5 in your code, it’s a very simple task that you need to perform.

First of all, it is necessary to obtain the location of the company. It will be easily obtained through the following function:

function addEmpresaMarker(latitude, longitude, marcadorEmp) {
  var coords = new google.maps.LatLng(latitude, longitude);
  marcadorEmp = new google.maps.Marker {
    map: map,
    position: coords
  };
}

Next, you need to know your user’s location. There is an HTML5 function that allows you to know the user’s location (use sparingly). Run it and add the coordinates in a new marker. Follow function below.

function findUserLocation(marcadorUsu) {
  // Mapa e opções do mapa já estão definidos previamente
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var posicao = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      console.log(posicao); // Confira se a localização está correta
      marcadorUsu = new google.maps.Marker {
        map: map,
        position: posicao
      };
    });
  } else {
    // Browser não suporta Geolocalização ou o usuário impediu o uso
    alert('Falha na tentativa de localização do usuário');
  }
}

Now, you need to calculate the route between the user and the company. For this, you will need the Google Maps Directions API, which will calculate distance and show the route, obviously. Note that in order to calculate the route, it needs references of the origin and destination markers. Note the function:

function mostrarCaminho (pointA, pointB) {
  // Aciona a Directions API
  var directionsService = new google.maps.DirectionsService;
  var directionsDisplay = new google.maps.DirectionsRenderer({
      map: mapa,
      suppressMarkers: true, // Não exibe os marcadores da rota, porque senão, pode confundir o usuário
  });
  directionsService.route({
    origin: pointA,
    destination: pointB,
    travelMode: google.maps.TravelMode.DRIVING
  }, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) { // Se deu tudo certo
      directionsDisplay.setDirections(response);
    } else {
      window.alert('Não foi possível exibir o trajeto devido ao seguinte erro: ' + status);
    }
  });
}

Now just join the commands you created in a single function that will be executed when the 'How to get there' button is clicked. The function should look something like this:

// AddEmpresaMarker()

var coordsEmp = new google.maps.LatLng(latitude, longitude);
marcadorEmp = new google.maps.Marker {
  map: map,
  position: coordsEmp
};

// FindUserLocation()
// Mapa e opções do mapa já estão definidos previamente

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    var posicao = {
      lat: position.coords.latitude,
      lng: position.coords.longitude
    };
    console.log(posicao); // Confira se a localização está correta
    marcadorUsu = new google.maps.Marker {
      map: map,
      position: posicao
    };
  });
} else {
  // Browser não suporta Geolocalização ou o usuário impediu o uso
  return alert('Falha na tentativa de localização do usuário'); // Esse return é pra finalizar a função. De nada adianta executar toda a função se você não tem uma das posições
}

// MostrarCaminho()
// Aciona a Directions API

var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
  map: mapa,
  suppressMarkers: true, // Não exibe os marcadores da rota, porque senão, pode confundir o usuário
});
directionsService.route({
  origin: pointA,
  destination: pointB,
  travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
  if (status == google.maps.DirectionsStatus.OK) { // Se deu tudo certo
    directionsDisplay.setDirections(response);
  } else {
    alert('Não foi possível exibir o trajeto devido ao seguinte erro: ' + status);
  }
});

There may be some syntax error in the middle, but it’s pretty quiet to correct. Any questions, comment. I’ll leave some links that can help you in this process:

Markers: https://developers.google.com/maps/documentation/javascript/markers?hl=pt-br

User location: https://www.w3schools.com/html/html5_geolocation.asp

Routes: https://developers.google.com/maps/documentation/directions/intro?hl=pt-br

-2

Dude is a hack, but it works.

I copied the link on the button and changed the destination:

<a href="http://maps.google.com/?saddr=Current%20Location&daddr=ENDEREÇO AQUI" target="_blank">COMO CHEGAR</a>

It’s exactly what the customer wants, it’s a gambit but it works

Browser other questions tagged

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