Leaflet 改变 Marker(标记) 颜色

方案一:

这是谷歌在设计Leaflet Icon时的最佳热门之一,但它没有一个没有第三方的解决方案,我在React中遇到了这个问题,因为我们需要动态颜色来处理路线和图标。

我想出的解决方案是使用Leaflet.DivIcon html属性,它允许您传递一个被评估为DOM元素的字符串。

例如,我创建了一个标记样式如下:

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中的背景颜色更改为您的自定义颜色,您就可以开始使用了。

 

方案二:

绑定这个网站的图标!

https://github.com/pointhi/leaflet-color-markers

网站上包含详细的操作方法信息。

 

用法:

var greenIcon = new L.Icon({
  iconUrl: 'https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png',
  shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  popupAnchor: [1, -34],
  shadowSize: [41, 41]
});

L.marker([51.5, -0.09], {icon: greenIcon}).addTo(map);

 

方案三:

试试 Leaflet.awesome-markers lib - 它允许你设置颜色和其他样式

1.首先,按照将Font-Awesome或Twitter bootstrap或Ionicons包含在您的应用程序中的步骤进行操作。

对于Font-Awesome,步骤位于:http://fortawesome.github.io/Font-Awesome/get-started/

对于Twitter bootstrap,步骤如下:http://getbootstrap.com/getting-started/

对于Ionicons:

你可以添加 ionicon stylesheet 从 https://ionicons.com/ ,或者直接在 head 引入以下内容:

<link rel="stylesheet" href="http://code.ionicframework.com/ionicons/1.5.2/css/ionicons.min.css">

2.接下来,将dist / images目录,awesome-markers.css和awesome-markers.js复制到项目中并包含它们:

<link rel="stylesheet" href="css/leaflet.awesome-markers.css">
<script src="js/leaflet.awesome-markers.js"></script>

3.现在使用插件创建一个这样的标记:

  // Creates a red marker with the coffee icon
  var redMarker = L.AwesomeMarkers.icon({
    icon: 'coffee',
    markerColor: 'red'
  });
      
  L.marker([51.941196,4.512291], {icon: redMarker}).addTo(map);

详细的用法可以参考github,这里我不在赘述。

相关资源也可以到我的CSDN下载,希望这篇文章能帮到大家!

leaflet-color-markers-master.zip

Leaflet.awesome-markers-2.0-develop.zip

 

  • 4
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值