带有打字稿的react-leaflet GeoJSON不呈现geojson点

react-leaflet GeoJSON with typescript not rendering geojson Points

我正在尝试使用 geojson 点将点渲染到地图上。我有一个反应应用程序,我正在使用反应传单。由于未知原因,不会在地图上呈现任何点。

我尝试导入 json 文件,但随后收到一条错误消息

      TS2322: Type '{ type: string; features: { type: string; properties: { name: string; amenity: string; popupContent: string; }; geometry: { type: string; coordinates: number[]; }; }[]; }' is not assignable to type 'GeoJsonObject'.
  Types of property 'type' are incompatible.
    Type 'string' is not assignable to type '"FeatureCollection" | "Feature" | "Point" | "MultiPoint" | "LineString" | "MultiLineString" | "Polygon" | "MultiPolygon" | "GeometryCollection"'.

我的 json 文件如下所示:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
          "name": "Coors Field",
          "amenity": "Baseball Stadium",
          "popupContent": "This is where the Rockies play!"
      },
      "geometry": {
          "type": "Point",
          "coordinates":  [59.433421, 24.75224]
      }
    }
  ]
}

我的地图代码:

import sensors from "./../Sensors/sensors.json";
import {TileLayer, MapContainer,GeoJSON} from "react-leaflet";
...

   <MapContainer
            style={{ height: "80vh", width: "100vw" }}
            center={center}
            zoom={12}
            scrollWheelZoom={true}
          >
            <TileLayer
              attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
            <Marker position={[59.43046, 24.728563]} title="Test">
              /{" "}
              <Popup>
                A pretty CSS3 popup. <br /> Easily customizable.
              </Popup>
            </Marker>
            <GeoJSON data={sensors} key="mydata" />
          </MapContainer>

我尝试的另一个解决方法是创建一个 .tsx 文件来导出一个变量,作为“数据”的预期对象类型

 export const featureCollection: GeoJSON.FeatureCollection<any> = {
      type: "FeatureCollection",
      features: [
        {
          type: "Feature" as "Feature",
          geometry: {
            type: "Point" as "Point",
            coordinates: [59.433421, 24.75224],
          },
          properties: {
            name: "SomeSensor",
          },
        },
      ],
    };

我所有的努力仍然没有解决方案。

任何人都可以建议我可能做错了什么吗?

确保您已安装 @types/leaflet@types/react-leaflet 以便能够获得这两个库中定义的类型。

您不必为 json

声明类型

还要确保覆盖默认值或使用 L.icon 以便能够在地图上看到标记 png 图像

这是一个工作 demo 你的例子