问题描述
有没有一种方法可以随机更改本机Leaflet中的标记颜色?我正在使用可以设置样式的svg元素.我知道mapbox.js可以实现
Is there a way to randomly change marker-colors in native Leaflet? I'm using svg elements which could be styled.I know that it is possible with mapbox.js
阐明我打算做什么:如果您通过双击或其他方式将标记添加到地图,则该标记应具有随机的颜色.为此,我想使用svg图标作为标记的样式.
To clarify what I intend to do: If you add markers to the map via a doubleclick or something it should have random colors. To achieve this I wanted to use svg icons for the markers to style them.
这是我的代码:
myIcon = L.icon({
iconUrl: "icon_33997.svg",
iconAnchor: pinAnchor
});
newMarker = L.marker(lat, long], {
icon: myIcon
});
推荐答案
因此,这是Google在设置Leaflet Icon样式方面的热门选择之一,但是它没有没有第三方的解决方案,而我一直在React中存在此问题,因为我们需要为路线和图标添加动态颜色.
So this is one of the top hits in Google for styling Leaflet Icon, but it didn't have a solution that worked without third parties, and I was having this problem in React as we needed dynamic colours for our routes and icons.
我想出的解决方案是使用 Leaflet.DivIcon html
属性,它允许您传递一个评估为DOM元素的字符串.
The solution I came up with was to use Leaflet.DivIcon html
attribute, it allows you to pass a string which is evaluated into a DOM element.
例如,我创建了一个标记样式,如下所示:
So for example I created a marker style follows:
const myCustomColour = '#583470'
const markerHtmlStyles = `
background-color: ${myCustomColour};
width: 3rem;
height: 3rem;
display: block;
left: -1.5rem;
top: -1.5rem;
position: relative;
border-radius: 3rem 3rem 0;
transform: rotate(45deg);
border: 1px solid #FFFFFF`
const icon = Leaflet.divIcon({
className: "my-custom-pin",
iconAnchor: [0, 24],
labelAnchor: [-6, 0],
popupAnchor: [0, -36],
html: `<span style="${markerHtmlStyles}" />`
})
将markerHtmlStyles
中的background-color
更改为自定义颜色,您就可以使用了.
Change background-color
in markerHtmlStyles
to your custom colour and you're good to go.
这篇关于传单更改标记颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!