简体   繁体   中英

Can I change the fillColor of a GeoJSON LineString with LeafLet

I have a GeoJSON full of LineStrings (elevation contours), which I'd like to plot on a MapBox/LeafLet map.

When plotted, all LineStrings seem to form polygons (ie first and last coordinates in the array are equivalent).

Is it possible to change the fillColor of the LineStrings, given they look like polygons anyway?

EDIT

Below is the code I currently have:

var elevation950Style = {
color : "yellow",
fillColor : "yellow",
opacity : 0.4,
weight : 2,
};

$.getJSON('950.geo.json', function(file) {
   L.geoJson( file ,  { style: elevation950Style } ).addTo(map);
});

It is certainly possible.

A good approach would probably be first to make sure your Line String is really a loop (as you say, if first and last coordinates are equal). Then simply convert it into a Polygon (create a new Polygon based on the same coordinates, remove the Line String), and it will be filled by Leaflet according to your fillColor option.


EDIT:

You could detect looped line strings after they are created by the L.geoJson() factory, create an equivalent GeoJSON feature with polygon geometry , and replace the looped line string by the newly created polygon within your GeoJSON layer group:

var myGeoJsonGroup = L.geoJson(myGeoJsonData), // build your GeoJSON layer group.
    geo, coords, first, last;

myGeoJsonGroup.eachLayer(function (layer) {
  geo = layer.feature.geometry;
  coords = geo.coordinates;
  first = coords[0];
  last = coords[coords.length - 1];

  if (geo.type === "LineString" && first[0] === last[0] && first[1] === last[1]) {
    myGeoJsonGroup.removeLayer(layer);
    myGeoJsonGroup.addData({
      type: "Feature",
      properties: layer.feature.properties,
      geometry: {
        type: "Polygon",
        coordinates: [
          coords // exterior linear ring
        ]
      }
    });
  }
});

myGeoJsonGroup.addTo(map);

Disclaimer: written as-is, not tested.

Note: in your case, you will certainly have elevation contours one within another. You may wish to build polygons with holes for the embedded contours. Otherwise, the fillings will stack, and you may not get your desired result if they are transparent.

If plotting line is the only criteria as SVG please check geojson2svg . You can just use CSS class in SVG path element or basic SVG's style. Check detailed examples here for understanding of this small module.

Disclaimer: I am author of geojson2svg

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM