使用 GetJSON,我失去了属性

问题描述

使用这个文件“segment.geojson”,我画了一个厚度为 20 的红色线段:

{
    "type": "FeatureCollection","features": [
        {
            "type": "Feature","properties": {
                "stroke": "#ff0000","stroke-width": 20,"stroke-opacity": 1
            },"geometry": {
                "type": "Linestring","coordinates": [[-3,48],[7,45]]
            }
        }
    ]
}

并使用 getJSON 将其显示在我的地图上:

    
<body>
    <div id="viewerDiv"></div>
    <script>
        window.onload= function() {
            var map = L.map("viewerDiv").setView([50,50],5) ;
            L.tileLayer(...blabla...).addTo(map);
            var segment = '';
            $.getJSON("segment.geojson",{dataType: "json"},function (data) {
                segment = new L.GeoJSON(data);
                map.fitBounds(segment.getBounds());
            })
            .done(function () {
                segment.addTo(map);
            });
        }
    </script>
</body>

但它是蓝色和厚1 !!!谁能帮我?提前谢谢你,JLC

来源在这里https://cavaliers23.fr/iti/ign/test_couleur.html

解决方法

您使用了错误的定义。您应该将样式作为第二个参数传递。

$.getJSON("segment.geojson",{ dataType: "json" },function (data) {
      segment = new L.GeoJSON(data,{
        style: {
          color: "#ff0000",weight: 20,opacity: 0.65,},});

您还可以使用属性字段将单独的样式传递给功能

"features": [
    {
      "type": "Feature","properties": {
        "color": "blue"
      },"geometry": {
        "type": "LineString","coordinates": [
          [-3,48],[7,45]
        ]
      }
    },{
      "type": "Feature","properties": {
        "color": "red"
      },"coordinates": [
          [-33,45]
        ]
      }
    }
$.getJSON("segment.geojson",{
        style: (f) => {
          switch (f.properties.color) {
            case "red":
              return {
                color: "#ff0000",};
            case "blue":
              return {
                color: "#0000ff",};
          }
        },});