perliedman / leaflet-routing-machine

Control for routing in Leaflet
https://www.liedman.net/leaflet-routing-machine/
Other
1.06k stars 347 forks source link

Question: How to assign L.Polyline from 'routeselected' event to global variable in TypeScript? #648

Closed Cronatsu closed 2 years ago

Cronatsu commented 2 years ago

First time Github user, I saw a question flair but I dunno how to add one to title.

This is my code:

map: L.Map;
path: L.Polyline;
leafletMap() {
            // Set the position and zoom level of the map
        this.map = L.map('mapId', {
            closePopupOnClick: false,
            scrollWheelZoom: false
        }).setView(<!--LatLng-->, 17);

        // Initialize the base layer
        L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
            maxZoom: 19
        }).addTo(this.map);
        const control = L.Routing.control({
                waypoints: route,<!--LatLng[]-->
                show: false,
                waypointMode: 'snap',
                createMarker: function() {}
            }).addTo(this.map);
            control.on('routeselected', function(c) {
                this.path = L.polyline(c.route.coordinates, {color: '#FF0000'}).addTo(this.map);
                this.map.removeControl(control);
            });
}

However I get this error for the "this.path" line:

Routing error: {status: -3, message: "TypeError: Cannot read property 'addLayer' of undefined"}

I can assign L.Map to a global variable but not anything under L.Routing.control (I tried just assigning c.route.coordinates). I need the LatLng[] from the routing control for other functions. Async did not work as I did before to resolve other global variable assignments in TypeScript. Anything that works?

Cronatsu commented 2 years ago

Never mind did not realize control.on requires async to return values, wish Leaflet had Promise support.