Search code examples
jsonmapboxmapbox-glmapbox-android

MapBox: How do I create a featureCollection programmatically?


I want to create clutering in my map. When looking at guides and in the Docs, the FeatureCollection Json is always pulled from some external link. But how do I just create it programmatically as I read data from my server? I don't have it all ready in one place and it will always be changing anyway depends on the user.

I've been stuck with this issue before and ended up using some duck tape solution, but it won't work now. Can anyone please shed some light on this please?


Solution

  • You're able to create a FeatureCollection using an existing Feature object or array/list of Feature objects. This could be turned into a method that you could use to generate a new FeatureCollection whenever you receive a new dataset.

    Given the information that you've provided, I am going to have to make some assumptions here - I hope that the following code snippet helps guide you in the right direction:

    public FeatureCollection getFeatureCollectionFromCoordinateList(List<Coordinate> coords) {
        List<Feature> pointsList = new ArrayList<>();
    
        for (Coordinate coord : coords) {
            Feature feature = Feature.fromGeometry(Point.fromLngLat(coord.getLongitude(), coord.getLatitude()));
            pointsList.add(feature);
        }
    
        return FeatureCollection.fromFeatures(pointsList);
    }
    

    In the above example, the object I've used to represent data from the server is called Coordinate which I've given a getLatitude() and getLongitude() method to demonstrate using latitudinal/longitudinal information to generate a Mapbox FeatureCollection from a List of Feature objects which are created using the Feature.fromGeometry() method, passing in a Point.fromLngLat().

    Please note that this mightn't be the best way to go about what you're trying to achieve here. That said, I hope it illustrates another way in which you can instantiate of FeatureCollection without reading in a JSON data source.