nbsa
nbsa

Reputation: 243

Trouble defining fill color for geojson attribute in Mapbox / Leaflet

I have loaded a geojson on a Mapbox map using

var featureLayer = L.mapbox.featureLayer()
            .loadURL('gmo_counties.geojson') 
            .addTo(map)

And the geojson is in the same directory as my index.html.

I would like to style the polygons in this geojson based on an attribute called "H_Sum_lbs". I have tried a couple of ways but haven't made any progress. How can I apply conditional coloring to these polygons based on the value of their "H_Sum_lbs" attribute?

Upvotes: 0

Views: 946

Answers (1)

iH8
iH8

Reputation: 28638

You could switch from L.mapbox.featureLayer to L.GeoJSON. It accepts a style function as an option where you can access the feature so you can conditionally return a style object based on your feature's properties:

var featureCollection = {
    "type": "FeatureCollection",
    "features": [{
        "type": "Feature",
        "properties": {
            "valid": false
        },
        "geometry": {
            "type": "LineString",
            "coordinates": [[-25, -25], [25, -25]]
        }
    }, {
        "type": "Feature",
        "properties": {
            "valid": true
        },
        "geometry": {
            "type": "LineString",
            "coordinates": [[25, 25], [-25, 25]]
        }
    }]
}

L.mapbox.accessToken = yourAccessToken;
var map = L.mapbox.map('mapbox').setView([0, 0], 0);

L.geoJson(featureCollection, {
    style: function (feature) {
        return {
            color: (feature.properties.valid) ? 'green' : 'red'
        }
    }
}).addTo(map);

L.GeoJSON reference: http://leafletjs.com/reference.html#geojson

L.Path options: http://leafletjs.com/reference.html#path

Upvotes: 3

Related Questions