Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

get distance problem #150

Closed
Doeran opened this issue Aug 29, 2015 · 3 comments
Closed

get distance problem #150

Doeran opened this issue Aug 29, 2015 · 3 comments

Comments

@Doeran
Copy link

Doeran commented Aug 29, 2015

Hi!

i have the following code

var routeControl = L.Routing.control({
createMarker : function() {
return null;
}
}).addTo(map);
var routee = new Array(); // array of latlng data
for (var i = 0; i < markersArray.length; i++)
routee.push(new L.LatLng(markersArray[i][0],
markersArray[i][1]));
routeControl.setWaypoints(routee);

but when i try get distance

routeControl._routes[0].summary.totalDistance

I get an error:
typeerror cannot read property 0 of undefined

Can you help me to fix this?

@SamSalman
Copy link

Hi,

I had the same prob and solved it with this:

window.L.Routing.control({
waypoints: coordinates,
routeWhileDragging: false,
addWaypoints: false,
draggableWaypoints: false,
waypointMode: 'connect',
lineOptions: {
styles: [{color: 'black', opacity: 0.15, weight: 9},
{color: 'white',opacity: 0.8, weight: 6},
{color: 'orange', opacity: 1, weight: 2}]}
}).addTo(window.map);

    var router = window.L.Routing.osrm();
    router.route(coordinates, (err, routes) => {
        //console.log(routes);
        if(routes !== undefined){
           console.log(routes[0].summary.totalDistance);
        }
    });

Where coordinates is an array =>
coordinates.push({latLng: L.latLng([lat, lon])});

Hope it helps.

@perliedman
Copy link
Owner

@Doeran like many things in JavaScript, the routing is asynchronous. Calling setWaypoints returns immediately to your code, before the route has been calculated.

You should probably use events to solve this. If you want to catch resulting routes when they are returned to the control for example, you should listen to the routesfound event:

routeControl.on('routesfound', function(e) {
    var routes = e.routes;
    [...]
});

If you're interested in every time the user selects a route, the routeselected event is more approriate.

Lastly, if you're not really interested in the UI, you could go with @SamSalman's solution above.

@Doeran
Copy link
Author

Doeran commented Aug 31, 2015

thank you a lot @perliedman.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants