Teiki
Teiki

Reputation: 200

Colorize polygons shapes from geoJSON in MapBox Android SDK

I'm using a geoJSON to display a shape in Android MapBox. In the geoJSON I've got a lot of polygons and each of them has a value in "properties" JSONObject, here is an exemple:

{
"geometry": {
    "type": "Polygon",
    "coordinates": [
        [
            [
                2.3303745,
                39.841098
            ],
            [
                2.3303464,
                39.8410976
            ],
            [
                2.3303261,
                39.8411054
            ]
        ]
    ]
},
"type": "Feature",
"properties": {
    "value": 169
}
}

I would like to fill the polygon with a specific colour according to the value.

What I currently do and get

GeoJsonSource geoJsonSource = new GeoJsonSource("geojson",stringbuilder.toString());
mapboxMap.addSource(geoJsonSource);
mapboxMap.addLayer(new FillLayer("geojson", "geojson"));

What I get

Question

What should I do to colorize the shape?

  1. Add in the JSON a "fill" value to "poperties" Object? (didn't work for me,yet.)
  2. Parse the JSON manually and use "fillColor" function in "PolygonOptions" object? (will add a lot of work, because there is a lot of polygons)

What I want

What I want

Upvotes: 0

Views: 1184

Answers (2)

Teiki
Teiki

Reputation: 200

JSONArray features = json.getJSONArray("features");

//Get the value for each features and create geojsonsource
for (int i = 0; i < features.length(); i++) {
    JSONObject feature = features.getJSONObject(i);
    Double value=-1.0;

    if (feature != null) {
        JSONObject properties = feature.getJSONObject("properties");
        if (properties != null && properties.has("value")) {
            value = properties.getDouble("value");
        }
        GeoJsonSource geoJsonSource = new GeoJsonSource("geojson" + i, feature.toString());

        if (!values.contains(value))
            values.add(value);
        list_value_geojson.add(new AbstractMap.SimpleEntry<>(value, geoJsonSource));
    }
}

in the postExecute function of my AsyncTask:

for (int i=0; i < list_value_geojson.size(); i++){
    Map.Entry<Double, GeoJsonSource> entry = list_value_geojson.get(i);
    if (mapboxMap != null && entry != null) {
        mapboxMap.addSource(entry.getValue());
        FillLayer fillLayer = new FillLayer(entry.getValue().getId(), entry.getValue().getId());
        fillLayer.setProperties(PropertyFactory.fillColor(Color.parseColor(hashMap    Colors.get(entry.getKey()))));
    mapboxMap.addLayer(fillLayer);

    }
}

Upvotes: 2

cammace
cammace

Reputation: 3168

Until data driven styling arrives in the next release, you'll need to create separate layers for each color and overlay them on top of each other. Contrary to what you might think, this shouldn't hinder performance, just a bit more work :)

Upvotes: 0

Related Questions