4

I have a World Countries geojson, that has country codes as "ID" (feature.id) and names as feature.properties.name

I would like to color specific countries for making a "countries visited" map.

What would be the easiest way to provide a list of ids or names to assign a color to them?

Currently my code for one country is this:

 var map = L.map('map').setView([30.45,24.61], 3);
 function style(feature) {
        if ("Latvia" == feature.properties.name) {
            return {
                weight: 2,
                opacity: 1,
                color: 'white',
                dashArray: '3',
                fillOpacity: 0.7,
                fillColor: '#FFA000'
            };
        } else {
            return {
                weight: 2,
                opacity: 1,
                color: 'white',
                dashArray: '3',
                fillOpacity: 0.7,
                fillColor: '#000'
            };
        }
    }

var geojsonLayer = new L.GeoJSON.AJAX("countries.geo.json", {
            style: style
        });       

geojsonLayer.addTo(map);

I would like to replace the "IF" thing with some sort of comma separated list of ids or names.

Here is a sample of that geojson file:

{"type":"FeatureCollection","features":[
{"type":"Feature","id":"AFG","properties":{"name":"Afghanistan"},"geometry":{"type":"Polygon","coordinates":
  • Is it possible to add a color attribute in your GeoJSON for each country? In Openlayers, you can use data form the GeoJSON to modify the style in a StyleMap. I do not know Leaflet but it probably has something similar – Mark Cupitt Oct 4 '14 at 16:48
7

From the Leaflet Polygon examples, here is one way with a Switch Statement:

var states = [{
"type": "Feature",
"properties": {"party": "Republican"},
"geometry": {
    "type": "Polygon",
    "coordinates": [[
        [-104.05, 48.99],
        [-97.22,  48.98],
        [-96.58,  45.94],
        [-104.03, 45.94],
        [-104.05, 48.99]
    ]]
}
}, {
"type": "Feature",
"properties": {"party": "Democrat"},
"geometry": {
    "type": "Polygon",
    "coordinates": [[
        [-109.05, 41.00],
        [-102.06, 40.99],
        [-102.03, 36.99],
        [-109.04, 36.99],
        [-109.05, 41.00]
    ]]
}
}];

L.geoJson(states, {
style: function(feature) {
    switch (feature.properties.party) {
        case 'Republican': return {color: "#ff0000"};
        case 'Democrat':   return {color: "#0000ff"};
    }
}
}).addTo(map);

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.