无法渲染GeoJSON数据React-Leaflet & Typescript

atmip9wb  于 2023-06-07  发布在  TypeScript
关注(0)|答案(1)|浏览(213)

我一直在尝试使用React Leaflet和Typescript渲染GeoJSON数据,但似乎无法让它工作。我很确定我的GeoJSON文件是好的,但typescript抱怨它不是正确的类型。如果这不是正确的类型,我就有点难住了,我应该传递GeoJSON组件。
错误消息获取:

Property 'type' is missing in type '({ type: string; geometry: { type: string; coordinates: number[]; }; properties: { prop0: string; prop1?: undefined; }; } | { type: string; geometry: { type: string; coordinates: number[][]; }; properties: { prop0: string; prop1: number; }; } | { ...; })[]' but required in type 'GeoJsonObject'.ts(2741)
index.d.ts(58, 5): 'type' is declared here.
GeoJSON.d.ts(7, 5): The expected type comes from property 'data' which is declared here on type 'IntrinsicAttributes & GeoJSONProps & RefAttributes<GeoJSON<any, Geometry>>'

下面是我使用的GeoJSON文件:

{ "type": "FeatureCollection",
  "features": [
    { "type": "Feature",
      "geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
      "properties": {"prop0": "value0"}
      },
    { "type": "Feature",
      "geometry": {
        "type": "LineString",
        "coordinates": [
          [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]
          ]
        },
      "properties": {
        "prop0": "value0",
        "prop1": 0.0
        }
      },
    { "type": "Feature",
       "geometry": {
         "type": "Polygon",
         "coordinates": [
           [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
             [100.0, 1.0], [100.0, 0.0] ]
           ]

       },
       "properties": {
         "prop0": "value0",
         "prop1": {"this": "that"}
         }
       }
    ]
  }

最后但并非最不重要的是我的react代码:

import test from "../test.json"
...

<MapContainer style={{height: 400, width: 600}} zoom={12} center={[0,0]}>
              {this.state.geoJSON && ( <GeoJSON attribution="NEOM Map Data" data={test.features}/> )}
            </MapContainer>

我还尝试将我的test json的值作为prop传递给我的map组件。在这种情况下, typescript 没有抱怨打字不正确,但似乎没有呈现任何东西?至少在我看来,我的Map是完全空的。

kx7yvsdv

kx7yvsdv1#

1.像之前的data={test}而不是data={test.features}一样修复TypeScript错误。下面是GeoJSON规范,显示您的json需要type https://datatracker.ietf.org/doc/html/rfc7946#section-3:

import test from "../test.json"
...

<MapContainer style={{height: 400, width: 600}} zoom={12} center={[0,0]}>
              {this.state.geoJSON && ( <GeoJSON attribution="NEOM Map Data" data={test}/> )}
            </MapContainer>

1.您的GeoJSON似乎是有效的:

1.为什么不尝试添加一个GeoJSON react key prop,如this(Rendering GeoJSON with react-leaflet)所指定的:

<MapContainer style={{height: 400, width: 600}} zoom={12} center={[0,0]}>
              {this.state.geoJSON && ( <GeoJSON key='my-geo-json' attribution="NEOM Map Data" data={test}/> )}
            </MapContainer>

相关问题