首页 > 解决方案 > 当我从 node_modules 导入leaflet.css 时未显示传单标记

问题描述

我有这个方法来添加标记到地图

createMarker(map) {
    if (this.state.node !== undefined) {
        const nodeLength = this.state.node.length;
        const latLang = [];
        this.state.node.map(item => latLang.push([item.latitude, item.longitude]));
        this.marker = [];

        // looping node
        for (let i = 0; i < nodeLength; i++) {
            this.marker[i] = L.marker(latLang[i]).addTo(map).on('click', () => this.handleClick(i));
        }
    } else {
        return 0;
    }
}

它在我在 index.html 中使用它时显示

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/>

但是当我在 index.js 中导入它时,它现在显示

import "leaflet/dist/leaflet.css"

标签: reactjsleaflet

解决方案


这是 webpack 和构建过程中文件捆绑的一个已经存在的问题,请检查#4968

为了克服这个问题,创建一个带有自定义图标的标记作为 L.icon 实例,如下所示:

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

...

createMarker(map) {
    if (this.state.node !== undefined) {
        const nodeLength = this.state.node.length;
        const latLang = [];
        this.state.node.map(item => latLang.push([item.latitude, item.longitude]));
        this.marker = [];

        // looping node
        for (let i = 0; i < nodeLength; i++) {
            this.marker[i] = L.marker(latLang[i], { icon }) // here pass icon as an option when creating markers
                                     .addTo(map)
                                     .on('click', () => this.handleClick(i));
        }
    } else {
        return 0;
    }
}

推荐阅读