【问题标题】:GeoJSON marker is not showing on my leafletjs mapGeoJSON 标记未显示在我的 Leafletjs 地图上
【发布时间】:2019-04-10 11:49:16
【问题描述】:

我正在编写我的第一个较大的 react 项目,我需要在我的地图组件中设置标记。我已经按照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 中引用的位置创建一个标记,但实际上唯一显示的是我的瓦片层。

【问题讨论】:

  • 嗨。你检查我的答案了吗?它回答了你的问题吗?
  • 是的,谢谢,对我帮助很大!但是我遇到了另一个困难,我不确定如何删除以这种方式创建的标记。
  • 请在新线程中将其作为新问题提出,您将获得帮助。我也去看看。

标签: reactjs leaflet


【解决方案1】:

在创建 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

【讨论】:

    【解决方案2】:

    欢迎来到 SO!

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

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

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

    然后解决构建引擎缺少处理默认图标图片的问题,见Leaflet #4968

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-09
      • 1970-01-01
      • 2018-03-30
      • 1970-01-01
      相关资源
      最近更新 更多