I'm trying to create a custom draw mode using the @mapbox/mapbox-gl-draw library. I want the mode to allow the user to create a route by placing points on the map. After each point is placed, I would like to call the Mapbox Map Matching API to find a route between the previous point and the current one, and then render the resulting line.
The problem I'm facing is that the line does not get rendered until another point is placed on the map, or the user switches modes. I'm guessing this issue is due to the fact that the API call to Map Matching returns a promise, although I'm the furthest thing from an expert on Mapbox (just started using it a few days ago).
I'll attach a video clip of the issue which hopefully does a better job of describing the problem than I can: https://streamable.com/ao3ger
The DrawRoute mode onClick function looks something like this:
DrawRoute.onClick = function (state, e) {
var point = this.newFeature({
type: 'Feature',
properties: {
count: state.count,
},
geometry: {
type: 'Point',
coordinates: [e.lngLat.lng, e.lngLat.lat],
},
});
const features = this._ctx.store._features;
if (Object.keys(features).length > 0) {
const lastPoint = getLastPointDrawn(features)
const coordinates = `${lastPoint.coordinates[0]},${lastPoint.coordinates[1]};${point.coordinates[0]},${point.coordinates[1]}`;
// This is an async function that makes a call to the Map Matching API and returns the line coordinates
getMatch(coordinates, [25, 25], 'walking').then((lineCoordinates) => {
// Add new line feature to object here using coords
const line = this.newFeature({
type: 'Feature',
properties: {},
geometry: {
type: 'LineString',
coordinates: lineCoordinates,
},
});
this.addFeature(line);
});
}
this.addFeature(point);
};
And here is the onDisplayFeatures method:
DrawRoute.toDisplayFeatures = function (state, geojson, display) {
display(geojson);
};
Does anybody have guidance on how Mapbox renders each feature? I can see that the DrawRoute object contains the new line features each time the user clicks, but they are not passed to toDisplayFeatures until the next point is created. Thanks!