3

New to Leaflet. I tried to set the fillColor to red. It is not working. I want each Polygon (there are less than 10 in this geoJSON) to have a unique color. Code is here:

<!DOCTYPE html>
<html>
   <head>
      <title>Leaflet sample</title>

      <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
  integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
  crossorigin=""/>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"
  integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
  crossorigin="anonymous"></script>

  <script src="https://unpkg.com/[email protected]/dist/jquery.js"></script>

      ...
      <!-- HTML Page Elements are here -->
   </head>

   <body>
      <div id = "map" style = "width: 1990px; height: 1000px">This is a Canvas</div>
      <script>

var newMap = L.map('map').setView([38.9188702,-77.0708398], 13);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href=”http://osm.org/copyright”>OpenStreetMap</a> contributors'
}).addTo(newMap);

var fillColor = "red"

$.getJSON("data/gpr.geojson",function(data){
// add GeoJSON layer to the map once the file is loaded
            var datalayer = L.geoJson(data ,{
                     onEachFeature: function(feature, featureLayer) {
                     featureLayer.bindPopup(feature.properties.NAME_1); { color: feature.properties.fillColor };
                     }
                     }).addTo(newMap);
                     newMap.fitBounds(datalayer.getBounds());
                     });



      </script>
   </body>`

1 Answer 1

3

If you look at the docs for L.geoJSON layer, you'll see that styling of GeoJSON features is done through style option, where you specify style function. This function receives feature as a parameter and must return style for that feature in the form of path options. There is a nice example of this in the Interactive Choropleth Map tutorial.

In your case code could then look something like this:

$.getJSON("data/gpr.geojson", function(data){
  var datalayer = L.geoJson(data, {
    onEachFeature: function(feature, featureLayer) {
      featureLayer.bindPopup(feature.properties.NAME_1);
    },
    style: function(feature) {
      return {
        fillColor: feature.properties.fillColor
      };
    }
  }).addTo(newMap);
  newMap.fitBounds(datalayer.getBounds());
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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