I'm currently using mapbox gl to visualise and analyse a GeoJSON layer of buildings. My current aim is to develop a function that will use the mapbox draw functionality to draw a line (using the lineString tool), then intersect this line with the building layer, output an array of coordinates for the intersect points and finally query rendered features of the building layer with the intersect point array.

function getIntersect() {
    var drawnLine = draw.getAll();
    var layerFeatures = turf.featureCollection(SELECTED_LAYER_JSON.features);
    var intersectingFeatures = turf.lineIntersect(drawnLine, layerFeatures);
    interArray = [];
    for (var i = 0; i < intersectingFeatures.features.length; i++) {

    mapB.on('render', interHeights);

This function above conducts the intersect using turf js functions to get the line and current building layer into the appropriate format.

function interHeights() {
    mapB.off('render', interHeights)
    var selectFeatures = [];
    interArray.forEach(coords => {
        pixelCoords = mapB.project(coords);
        var bbox = [[pixelCoords.x - 10, pixelCoords.y - 10], [pixelCoords.x + 10, pixelCoords.y + 10]];
        selectFeatures.push(mapB.queryRenderedFeatures(pixelCoords, {layers: [SELECTED_LAYER_ID]}));

The function above iterates through the intersect coordinate array and creates an array of features using queryRenderedFeatures.

Here is a bl.ock where you can see an example of the code.

Sadly the later function is not working correctly it currently is intermittently returning features in the query rendered feature array (selectFeatures). While the intersect works well and gives out an array of all intersected points, the query rendered feature function only returns query results for some intersect points and not others. This often depends on map zoom level or movement and changes depending on amount of buildings intersected with the drawnline. All results should be visible in the console.

I have subsequently read a post about the asynchronous nature of addLayer but I'm not sure if this is the problem I'm experiencing, but I was wondering if anyone has any suggestions or had experienced similar issues with the query rendered feature function in mapbox before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.