Generate route with Maps API

1

I am working with the Google Maps API and I wanted to generate the route between two points but I do not know very well how. I have been reading the documentation and I see that it has to be defined using the parameters origin: and destination: but it is not clear to me where I should define it.

Can anyone help me?

My intention is that if you click on the trace button, the route will be generated.

Cheers!

$(document).ready(function() {

  function localizacion(posicion) {
    // Coordenadas oficina
    var latitud = 39.579745;
    var longitud = 2.654018;

    //Generamos el mapa que muestre y cual será el punto central
    var map = new google.maps.Map(document.getElementById('Mapa'), {
      center: {
        lat: latitud,
        lng: longitud
      },
      zoom: 14
    });

    //Generamos el marcadores para señalar una posición
    var markerMiPosicion = new google.maps.Marker({
      position: {
        lat: latitud,
        lng: longitud
      },
      title: "Ubicación oficina estudiante"
    });

    // Mostramos los marcadores en el mapa.
    markerMiPosicion.setMap(map);

    // Si clican sobre botón ubicación usuario
    $('#UbicacionPersonal').click(function() {
      // Obtenemos coordenadas
      var latitudReal = posicion.coords.latitude;
      var longitudReal = posicion.coords.longitude;

      // Generamos un marcador
      var markerPosicionReal = new google.maps.Marker({
        position: {
          lat: latitudReal,
          lng: longitudReal
        },
        title: "Mi actual ubicación"
      });

      // Lo mostramos sobre el mapa.
      markerPosicionReal.setMap(map);
    });

    $('#TrazarRuta').click(function() {
      origin: latitudReal,
      longitudReal;
      destination: latitud,
      longitud;
    });

  }

  // En caso de no poder geolocalizar hay que tener un mensaje de error (o acción)
  function error() {
    alert('No se puede obtener tu ubicación actual')
    // un error a valorar es que el usuario no permite la geoloc, code:1
  }

  // Ahora empleamos todo lo declarado anteriormente.
  // Comprobamos si el navegador soporta la geolocalización
  if (navigator.geolocation) {
    //Caso SI soporta geolocalización. Ejecuto la API y llamo a mis funciones.
    navigator.geolocation.getCurrentPosition(localizacion, error);
  } else {
    //Caso NO soporta geolocalización
    alert('Navegador NO soporta geolocalización');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="Mapa"></div>

<div id="Info-Mapa">
  <div class="ExtraInfo" id="Como-Llegar">
    <p class="Texto" id="Texto-Llegar">
      A continuación puedes ver tu ubicación actual.
    </p>
    <input type="button" class="BotonMap" id="UbicacionPersonal" value="Mi ubicación">
    <p class="Texto">
      También puedes trazar la ruta hasta la oficina en coche.
    </p>
    <input type="button" class="BotonMap" id="TrazarRuta" value="Trazar">
  </div>
</div>
    
asked by NEA 20.02.2018 в 15:56
source

1 answer

2

Short answer: here is a working fiddle .

Long answer:

First: Your map is initialized once you know the coordinates of the visitor. As you put an arbitrary center and the visitor can be in Vladivostok, there will hardly be a route available, so I changed your code to fix the center of the map (and the first marker) relatively close to the visitor's location using Math.random() .

var randomLat = Math.random(),
  randomLng = Math.random();;

randomLat = (randomLat < 0.5) ? -1 * randomLat : randomLat - 0.5;
randomLng = (randomLng < 0.5) ? -1 * randomLng : randomLng - 0.5;

var latitudReal = posicion.coords.latitude,
  longitudReal = posicion.coords.longitude,
  latitud = latitudReal + randomLat/10,
  longitud = longitudReal + randomLng/10;

Second: You need to instantiate an object google.maps .DirectionsService to request routes, and an object google.maps.DirectionsRenderer to draw the result on the map.

//Generamos el mapa que muestre y cual será el punto central
var map = new google.maps.Map(document.getElementById('Mapa'), {
  center: {
    lat: latitud,
    lng: longitud
  },
  zoom: 14
});

var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);

Finally, since you know the center of the map and the visitor's position:

$('#TrazarRuta').click(function () {
  directionsService.route({
    origin: markerInicial.getPosition(),
    destination: {
      lat: latitudReal,
      lng: longitudReal
    },
    travelMode: 'DRIVING'
  }, function (response, status) {
    if (status === 'OK') {
      directionsDisplay.setDirections(response);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
});

The object of options that you give to the route method supports different methods of travel (driving, walking, cycling, public transport), and intermediate points if you want the route to pass through them.

The directionsDisplay object also supports options, such as styling the polyline, making it draggable, and more.

    
answered by 21.02.2018 / 14:53
source