use*_*217 8 javascript leaflet react-leaflet
我有非常简单的代码来使用react-leaflet显示地图并在其上放置标记.但是,我在浏览器控制台中收到以下两个错误
GET http:// localhost:8080/marker-icon-2x.png 404(未找到)
GET http:// localhost:8080/marker-shadow.png 404(未找到)
我尝试通过下载这两个图像并将它们放在根目录来解决此问题.有用.但是,如何更改react-leaflet标记元素查找标记图像的URL?我想将它们存储在"./images"而不是根目录中.
Ste*_*sic 19
试着这样做:)
由于某种原因,React传单不包含图像,您需要重置默认图标图像.
下面是一些工作示例,我希望它能解决您的问题.
您还可以从其中一个公共链接添加图标
https://cdnjs.com/libraries/Leaflet.awesome-markers
import React, { Component } from 'react';
import L from 'leaflet';
import {
Map, TileLayer, Marker, Popup
} from 'react-leaflet'
import 'leaflet/dist/leaflet.css';
import './style.css';
import icon from 'leaflet/dist/images/marker-icon.png';
import iconShadow from 'leaflet/dist/images/marker-shadow.png';
let DefaultIcon = L.icon({
iconUrl: icon,
shadowUrl: iconShadow
});
L.Marker.prototype.options.icon = DefaultIcon;
Run Code Online (Sandbox Code Playgroud)
Gro*_*ile 15
这是对我有用的解决方案:
我在文件顶部添加了以下几行:
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import L from 'leaflet';
delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.mergeOptions({
iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png').default,
iconUrl: require('leaflet/dist/images/marker-icon.png').default,
shadowUrl: require('leaflet/dist/images/marker-shadow.png').default
});
Run Code Online (Sandbox Code Playgroud)
ch4*_*d4n 14
添加 Next.js 的答案
将标记图标从复制node_modules/leaflet/dist/images到public/images类似的内容/images/marker-icon.png
创建传单图标引用并在标记中使用该引用
const icon = L.icon({ iconUrl: "/images/marker-icon.png" });
// some other code
<Marker key={obj.id} position={position} icon={icon}>
// rest of the code
Run Code Online (Sandbox Code Playgroud)
小智 5
在使用 react、leaflet 和 react-leaflet 时,似乎并非所有东西都正确集成在一起。我有同样的问题,发现这个
https://github.com/PaulLeCam/react-leaflet/issues/453
您需要再次设置 Leafelet 本身,因为在导入 Leaflet.css 后会出现问题。
希望能帮助到你
小智 5
将传单包中的所有图像复制到公共目录:
cp node_modules/leaflet/dist/images/* {PUBLIC_WEB_DIRECTORY}/leaflet_images/
Run Code Online (Sandbox Code Playgroud)
修复Leaflet中的路径
import L from 'leaflet';
L.Icon.Default.imagePath='leaflet_images/';
Run Code Online (Sandbox Code Playgroud)