[英]How to set marker icon in leaflet map?
I have my component MAP and I use leaflet (not react-leaflet).我有我的组件 MAP,我使用传单(不是反应传单)。 I want to set a marker.我想设置一个标记。
This is the code of my component.这是我的组件的代码。
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" />
}
}
I add the marker us described in the documentation, but the result in the map is not the default icon, it is only a square with a thin border.我添加了我们在文档中描述的标记,但地图中的结果不是默认图标,它只是一个带有细边框的正方形。 I checked the css-File from leaflet.我检查了传单中的 css-File。 The icon is in the images folder, but it is not in the map available.该图标位于图像文件夹中,但不在可用地图中。
This icon (marker) I am looking for我正在寻找的这个图标(标记)
Can anybody help or see what is wrong with my code?有人可以帮忙或看看我的代码有什么问题吗?
This is a well known css bundle issue with webpack.这是一个众所周知的 webpack css bundle 问题。 Define markerIcon as将标记图标定义为
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"
});
and assign it to the icon property of L.marker
like this:并将其分配给L.marker
的 icon 属性,如下所示:
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();
As per your question, I can interpret that you are not able to import the CSS properly.根据您的问题,我可以解释您无法正确导入 CSS。
You can import the css for the leaflet module by writing您可以通过编写为传单模块导入 css
import 'leaflet/dist/leaflet.css';
For detailed explanation you can read有关详细说明,您可以阅读
Do I have to import leaflet's CSS file? 我必须导入传单的 CSS 文件吗?
Example of how to load static CSS files from node_modules using webpack? 如何使用 webpack 从 node_modules 加载静态 CSS 文件的示例?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.