react leaflet 有一个破损的标记
2021-10-04
1205
我已导入 Leaflet 模块以及一些代码来删除图标。
import L from "leaflet";
import { Map, TileLayer, Marker, Popup } from "react-leaflet";
import "leaflet/dist/leaflet.css";
delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.mergeOptions({
iconRetinaUrl: require("./images/marker-icon-2x.png"),
iconUrl: require("./images/marker-icon.png"),
shadowUrl: require("./images/marker-shadow.png"),
});
标记图标位于我的图像文件夹中。 我也尝试直接要求:
L.Icon.Default.mergeOptions({
iconRetinaUrl: require("leaflet/dist/images/marker-icon-2x.png"),
iconUrl: require("leaflet/dist/images/marker-icon.png"),
shadowUrl: require("leaflet/dist/images/marker-shadow.png"),
});
但我仍然得到一个损坏的标记。
2个回答
如果您使用的是
create-react-app
,这应该适用于 Webpack 配置。您必须将此代码放在某个位置,以便它在
<Marker>
元素呈现之前执行,例如在
App.tsx
文件的顶部:
import L from 'leaflet';
import markerIcon2x from 'leaflet/dist/images/marker-icon-2x.png';
import markerIcon from 'leaflet/dist/images/marker-icon.png';
import markerShadow from 'leaflet/dist/images/marker-shadow.png';
delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.mergeOptions({
iconUrl: markerIcon,
iconRetinaUrl: markerIcon2x,
shadowUrl: markerShadow,
})
teddybeard
2021-10-05
使用 leaflet-defaulticon-compatibility 插件,它应该不需要进一步的代码就可以工作,前提是你的构建引擎配置已经设置为处理 CSS 中的 URL:
$ npm install leaflet-defaulticon-compatibility --save
import 'leaflet/dist/leaflet.css';
import 'leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.webpack.css'; // Re-uses images from ~leaflet package
import * as L from 'leaflet';
import 'leaflet-defaulticon-compatibility';
Disclaimer: I am the author of that plugin
ghybs
2021-10-07