Listen for click events on a LineLayer

Viewed 535

Various lines are added to the map representing routes using the following code:

private LineLayer makeLineLayer(List<GeoPoint> routePoints, String title) {

    String sourceTitle = "line-layer-" + lineCount;

    List<Position> points = new ArrayList<>(routePoints.size());
    List<Feature> routes = new ArrayList<>(routePoints.size());
    for (GeoPoint point : routePoints) {
            points.add(Position.fromCoordinates(point.getLongitude(), point.getLatitude()));
    }
    LineString route = LineString.fromCoordinates(points);

    Feature routeFeature = Feature.fromGeometry(route);
    routeFeature.addStringProperty("custom-line", "0");
    routes.add(routeFeature);

    GeoJsonSource linesSource = new GeoJsonSource(
                sourceTitle,
                FeatureCollection.fromFeatures(routes));
    mapboxMap.addSource(linesSource);

    LineLayer lineLayer = new LineLayer(title, sourceTitle);
    lineLayer.setProperties(
        //Sets properties...
    );

    return lineLayer;
}

LineLayer lineLayer = makeLineLayer(getRoutePoints());
mapboxMap.addLayer(lineLayer);

I'd like to be able to determine when one of these lines is clicked. Currently, MapBox calls OnMapClick and passes in a LatLng object. I can then query for rendered features with the custom-line property using the following:

PointF pixel = mapboxMap.getProjection().toScreenLocation(point);
List<Feature> selectedKeys = mapboxMap.queryRenderedFeatures(pixel, Filter.has("custom-line"));

If selectedKeys then contains any returned Feature objects, I can query for their coordinates with .getGeometry(). Comparing those values with those from the LatLng object that was passed in, a rough estimate of which line was clicked can be determined. However, this is very inaccurate and troublesome when the line items are closely grouped.

How would one listen for click events on these line items?

1 Answers
Related