Leaflet标记渲染但显示“损坏的图像”占位符

4
这是它的样子:

1

我的代码:

Map.js

//the next 3 lines changes nothing kept it in bc I found this online as a potential solution
//and didn't want to get this suggested
import L from 'leaflet';
delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.imagePath = "/";

function Map() {

 let position = [x, y];

 return (
   <div>
     <div id="mapid">
       <MapContainer className="leaflet" center={position} zoom={13} scrollWheelZoom={true}>
         <TileLayer
           attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
           url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
         />
          <Marker position={position}>
            <Popup>
              A pretty CSS3 popup. <br /> Easily customizable.
            </Popup>
          </Marker>
        </MapContainer>
      </div>
    </div>

  );
};

index.css

.leaflet {
  height: 500px;
  width: 100%;
}

#mapid {
  height: 500px;
  margin-top: 50px;
  margin-bottom: 150px;
}

img.leaflet-marker-icon {
   background-image: 
   url('<url>');
}

我真的不明白标记器是如何同时渲染和不渲染的,这毫无意义。
显然,我正在尝试呈现某些图像,但我不知道是哪个导致了它不被呈现。
代码基本上来自示例代码:https://leafletjs.com/examples/quick-start/。这就是我感到困惑的原因。
我已经在index.html中包含了样式和脚本标记。
2个回答

1
如果你非常仔细地观察,实际上在你的截图中有2个损坏的图像占位符:
  • 一个比Marker图标图像更宽:那是默认的Leaflet图标阴影图像:

leaflet marker icon shadow image

  • 另一个更难辨认的是,它适合所显示的图标图像大小:这是实际默认 Leaflet 蓝色图标图像,在 <img> 标签的 src 属性中指定。但我们可以看到蓝色图标,因为您已将其指定为背景图像(但仍然损坏,因此浏览器仍显示占位符)。

根本原因是您的构建引擎(最可能是 webpack,因为您使用 React)重写了 Leaflet CSS 文件中的 URL,这会干扰 Leaflet 用于检测其图像路径的方式。

有关更多详细信息,请参见 Leaflet/Leaflet#4968PaulLeCam/react-leaflet#453

至于解决方法,您有两个可能的简单选项:

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';
  • 在您的项目中某处使用此代码片段(您可能需要正确配置webpack加载器):
import 'leaflet/dist/leaflet.css';
import * as L from 'leaflet';
delete L.Icon.Default.prototype._getIconUrl;

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'),
});

0

我在这里找到了答案:

import { icon } from "leaflet"

const ICON = icon({
  iconUrl: "/marker.png",
  iconSize: [32, 32],
})

...

<Marker icon={ICON} ... />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接