leaflet-routing-machine
leaflet-routing-machine copied to clipboard
Load route from variable
Hi, My project is based on angularjs. I'm saving route by using:
control.on('routeselected', function (e) {
tripRoute = JSON.stringify(e.route);
});
and save this to a database. Later when trying to load the route
control.setAlternatives(JSON.parse($scope.trip.lineString)); I'm getting:
TypeError: this._routes.slice is not a function at L.Routing.Itinerary.L.Control.extend.setAlternatives (leaflet-routing-machine.js:1166)
Yes, set alternatives takes an array of routes (the alternatives), but it looks like you're passing a single route.
control.setAlternatives([JSON.parse($scope.trip.lineString)]);
would probably fix this.
Thank you for your answer, but now I'm getting:
TypeError: wpLatLng.distanceTo is not a function at L.Routing.Line.L.LayerGroup.extend._extendToWaypoints (leaflet-routing-machine.js:1451) at L.Routing.Line.L.LayerGroup.extend.initialize (leaflet-routing-machine.js:1395)
Can it be that after deserialization the L.LatLng became just object?
coordinates: Array[4]
0: Object
lat: 47.104417
lng: 28.879413
__proto__: Object
1: Object
2: Object
3: Object
Yes, you are right. I remember that the code assumes a route's coordinates to be L.LatLng instances since a couple of versions back.
As a hack, you can of course make the coords into latlngs when deserializing, but maybe there should be some change in LRM to make this easier.
Please have you solved this problem: control.setAlternatives([JSON.parse($scope.trip.lineString)]);
@esurnet as mentioned above, the issue is that the JSON's coordinates property isn't deserialized to an array of LatLng objects, which setAlternatives expect. As a workaround, you can parse the JSON and then convert the coordinates array to LatLngs.
A pull request to address this would be welcome, but my own time for developing Leaflet Routing Machine is very limited at the moment, so don't expect me to address this any time soon.
Thanks
I had the same problem and yes, it is to do with the LatLng object. I appear to have found a fix with a minor edit to the source code of leaflet-routing-machine.js
The problem can be traced to in _extendToWayPoints method:
wpLatLng = L.latLng(wps[i].latLng); routeCoord = this._route.coordinates[wpIndices[i]];
The first variable has been cast using Leaflet L.latLng, but not the second, where it blows out.
routeCoord = L.latLng(this._route.coordinates[wpIndices[i]]);
appears to solve the problem for me...
its working!
let route = JSON.parse(...);
route.inputWaypoints.map(e => e.latLng = L.latLng([e.latLng.lat, e.latLng.lng])); // **fix latLng**
control.setAlternatives([route]);