我的leafletjs地图上没有显示GeoJSON标记

问题描述 投票:1回答:2

我正在编写我的第一个更大的项目,我需要在我的地图组件中设置标记。我已经设置了所有内容,因为它在tutorial中显示但是它与我的代码无法正常工作并且标记未在地图上显示。

const dummyGeoJson = {
  type: "FeatureCollection",
  features: [
    {
      type: "Feature",
      properties: {},
      geometry: {
        type: "Point",
        coordinates: [16.959285736083984, 52.40472293138462]
      }
    }
  ]
};

class EventMap extends React.Component {
  componentDidMount() {
    this.map = L.map("map", {
      center: [51.9194, 19.1451],
      zoom: 6
    });

    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
      maxZoom: 20
    }).addTo(this.map);
    var geoJsonLayer = L.geoJSON().addTo(this.map);
    geoJsonLayer.addData(dummyGeoJson);
  }

  render() {
    return <Wrapper width="100%" height="800px" id="map" />;
  }
}

从我在官方传单教程中看到的内容,这段代码应该创建一个新的geojson层并在geojson中引用的位置创建一个标记,但实际上唯一显示的是我的tile层。

reactjs leaflet
2个回答
0
投票

在创建GeoJSON层时,您需要在GeoJSON选项对象中使用pointToLayer函数,如下所示:

componentDidMount() {
    const map = L.map("map", {
      center: [51.9194, 19.1451],
      zoom: 6
    });

    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
      maxZoom: 20
    }).addTo(map);

    L.geoJSON(dummyGeoJson, {
      pointToLayer: (feature, latlng) => {
        return L.marker(latlng, { icon: customMarker });
      }
    }).addTo(map);
}

然后,您可以传递customMarker变量来定义一些选项,以使您的标记显示在UI上

Demo


0
投票

欢迎来到SO!

最可能的原因是您捆绑了您的应用程序(通常使用webpack),但构建错过了Leaflet默认图标图像。

所以你的Marker就在那里,但你看不到它,因为它的图标图像丢失了。

一种简单的调试方法是使用另一个图标,如kboul's answer中所建议的那样,或者更简单地使用CircleMarker。

然后要解决缺少构建引擎以处理默认图标图像的问题,请参阅Leaflet #4968

  • 显式导入/要求Leaflet默认图标图像并修改L.Icon.Default选项以使用新导入的路径
  • 或使用leaflet-defaulticon-compatibility插件(我是作者)。
© www.soinside.com 2019 - 2024. All rights reserved.