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>