【问题标题】:How to set marker icon in leaflet map?如何在传单地图中设置标记图标?
【发布时间】:2019-11-27 05:22:45
【问题描述】:

我有我的组件 MAP,我使用传单(不是 react-leaflet)。 我想设置一个标记。

这是我的组件的代码。

import React from 'react';
import L from 'leaflet';
import '../../../../node_modules/leaflet/dist/leaflet.css';
import './map.scss';



export default class Map extends React.Component {


  componentDidMount() {

    this.map = L.map('map', {
      center: [48.8762, 2.357909999999947],
      zoom: 14,
      zoomControl: true,
      layers: [
        L.tileLayer('https://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png',{
          detectRetina: true,
          maxZoom: 20,
          maxNativeZoom: 17,
        }),
      ]
    });

    L.marker([48.8762, 2.357909999999947],
      {
        draggable: true,        // Make the icon dragable
        title: 'Hover Text',     // Add a title
        opacity: 0.5}            // Adjust the opacity
    )
      .addTo(this.map)
      .bindPopup("<b>Paris</b><br>Gare de l'Est")
      .openPopup();

    L.circle([48.8762, 2.357909999999947], {
      color: 'red',
      fillColor: '#f03',
      fillOpacity: 0.5,
      radius: 500
    }).addTo(this.map);

  };


  render() {
    return <div className="map" id="map" />
  }
}

我添加了我们在文档中描述的标记,但是地图中的结果不是默认图标,它只是一个带有细边框的正方形。 我从传单中检查了 css 文件。该图标位于图像文件夹中,但不在可用的地图中。

我正在寻找这个图标(标记)

这就是我得到的

谁能帮忙看看我的代码有什么问题?

【问题讨论】:

  • 你能粘贴想要的和实际的截图吗?
  • 代替import '../../../../node_modules/leaflet/dist/leaflet.css';尝试写import 'leaflet/dist/leaflet.css';
  • @iamsaksham 不,它不是重复的
  • 你能在网络标签(开发者控制台)中看到被请求的图标 png 文件吗?

标签: javascript reactjs leaflet


【解决方案1】:

这是一个众所周知的 webpack 的 css bundle 问题。将markerIcon定义为

const markerIcon = L.icon({
  iconSize: [25, 41],
  iconAnchor: [10, 41],
  popupAnchor: [2, -40],
  // specify the path here
  iconUrl: "https://unpkg.com/leaflet@1.5.1/dist/images/marker-icon.png",
  shadowUrl: "https://unpkg.com/leaflet@1.5.1/dist/images/marker-shadow.png"
});

并将其分配给L.marker 的图标属性,如下所示:

 L.marker(
      [48.8762, 2.357909999999947],
      {
        draggable: true, // Make the icon dragable
        title: "Hover Text", // Add a title
        opacity: 0.5,
        icon: markerIcon // here assign the markerIcon var
      } // Adjust the opacity
    )
      .addTo(this.map)
      .bindPopup("<b>Paris</b><br>Gare de l'Est")
      .openPopup();

Demo

【讨论】:

    【解决方案2】:

    根据您的问题,我可以解释为您无法正确导入 CSS。

    你可以通过编写来导入leaflet模块的css

    import 'leaflet/dist/leaflet.css';

    详细解释可以阅读

    Do I have to import leaflet's CSS file?

    Example of how to load static CSS files from node_modules using webpack?

    【讨论】:

      猜你喜欢
      • 2022-12-01
      • 2019-11-22
      • 2016-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多