Closed VicQP closed 6 years ago
Hi, it's hard to tell what the problem is without seeing some code that gives this problem. If you can give an example of what you're trying to do, I might be able to help out.
Hola muchas gracias por responder. Estoy tratando de obtener y devolver la distancia a traves del evento "routesfound" pero al devolverlo recivo un valor "undefined". Te anexo el codigo esperando algun consejo, gracias. `function ruteo(lat_1, lon_1, lat_2, lon_2) { var distance; // Calculo de la ruta ruta = L.Routing.control({ waypoints : [ L.latLng(lat_1, lon_1), L.latLng(lat_2, lon_2) ] }).addTo(map);
// Obtiene a traves del evento generado la distancia y el tiempo
ruta.on('routesfound', function (e) {
distance = e.routes[0].summary.totalDistance; // Distancia
//time = e.routes[0].summary.totalTime; // Tiempo
});
return distance;
}`
Sorry, my Spanish is not very good, so I might be missing details from what you wrote.
However, that code looks like it should run without undefined values. Can you make a running example that shows the problem?
Hi, look at this is a part of the code where I'm trying to use it. ` $.getJSON('./paradas.json', function(data) { var orlat = "19.594266"; var orlon = "-99.227220"; //tamaño = data.paradas.length; // Total de datos console.log("lat: " + data.paradas[4].direccion.lat + " lon: " + data.paradas[4].direccion.lon) console.log("lat: " + orlat + " lon: " + orlon) // Calcular la distancia entre 2 puntos console.log(ruteo(data.paradas[4].direccion.lat, data.paradas[4].direccion.lon, orlat, orlon)); });
`
And the function where I get the distance is this.
` function ruteo(lat_1, lon_1, lat_2, lon_2) { var distance; // Calculo de la ruta ruta = L.Routing.control({ waypoints : [ L.latLng(lat_1, lon_1), L.latLng(lat_2, lon_2) ] }).addTo(map);
// Obtiene a traves del evento generado la distancia y el tiempo
ruta.on('routesfound', function (e) {
distance = e.routes[0].summary.totalDistance; // Distancia
//time = e.routes[0].summary.totalTime; // Tiempo
});
return distance;
}
`
What I try to do is keep the calculated distance inside a varibale to be able to continue using it. Thank you.
The issue here is that you are trying to return the distance ruteo
function, but since route finding is asynchronous, the distance
variable will not be assigned a value until the routesfound
callback is called, which will not be until after the return distance
has run.
I suggest you read up on asynchronous programming in JavaScript as well as event handling (which is one application of asynchronous programming).
Also, be aware that for something like this you would probably want to use LRM's L.Routing.OSRMv1
class directly instead of using the control UI.
Hi, when I get the distance through the Summary of IRoute, how can I save it in an array for later use? Because doing so I get an "undefined" value