传单更改标记颜色 [英] Leaflet changing Marker color

查看:82
本文介绍了传单更改标记颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以随机更改本机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

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.

这篇关于传单更改标记颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆