Search code examples
javascripthtmlleafletgeojson

How to change the colours of markers based on properties in leaflet?


enter image description here

I have the above map and the markers have properties 'rastvalues'. I want to change the marker colour based on 'rastvalues' values.Below is my javascript code

<script type="text/javascript" >
        function main_map_init (map, options) {
             var promise  = $.getJSON('{% url "datapotg" %}');
            // Download GeoJSON via Ajax
            promise.then(function(data) {
            var allbusinesses = L.geoJson(data);
            var cafes = L.geoJson(data, {
            filter: function(feature) {

                return feature.properties.rastvalues ;

                },
                pointToLayer: function(feature, latlng) {
                return new L.CircleMarker(latlng, {
                radius: 8,
                    fillColor: "Red",
                    color: "Red",
                    weight: 1,
                    opacity: 1,
                    fillOpacity: 0.4,
                    clickable: true

                }).on('mouseover', function() {
                    this.bindPopup(feature.properties.rastvalues).openPopup();
                });
            }
        });


         map.fitBounds(allbusinesses.getBounds(), {
            padding: [50, 50]
        });
        cafes.addTo(map)


        });
        }

    </script>

I have rastvalues =3,rastvalues =9,rastvalues =12 How can I give different colours for these three values ?


Solution

  • You could create an object containing your values and their repective colors and retreive them from it using bracket notation. Some people recommend using a function but i think using an object is easier:

    pointToLayer: function (feature, latlng) {
        var colors = {
            3: 'green',
            9: 'orange',
            12: 'red'
        };
        return new L.CircleMarker(latlng, {
            radius: 8,
            fillColor: colors[feature.properties.rastvalues],
            color: colors[feature.properties.rastvalues],
            weight: 1,
            opacity: 1,
            fillOpacity: 0.4,
            clickable: true
        }
    });