Leaflet custom icon marker rotate an angle, the transform style conflict
Asked Answered
G

1

7

I reproduced this issue with the following demo: http://jsfiddle.net/baoqger/deL0yuvg/9/

In my project, I have a custom icon marker which I want to rotate the icon on some cases.

I add a claasname when the icon is created:

const uturnIcon = L.icon({
  iconUrl: 'http://joshuafrazier.info/images/firefox.svg',
  iconSize: [30, 30],
  className: 'u-turn-icon'
})

and add css style for the class as following:

.u-turn-icon {
  transform: rotate(20deg) !important
}

The problem is by default, the icon img has a style attribute of transform: translate3d, so there is conflict between the default transform and my added transform style. And the default transform style is created by leaflet itself, when we zoom the map, the value for this attribute is updated as well.

So how to solve this issue?

Gainly answered 19/1, 2019 at 3:26 Comment(1)
github.com/bbecquet/Leaflet.RotatedMarkerInstalment
M
6

The first problem with your code is that it rotates the icon around its corner rather than its centre, so it ends up in the wrong place. The second problem is that Leaflet uses the icon's style.transform property to position it, so the rotation gets over-ridden every time the map zooms.

The Leaflet.RotatedMarker plugin suggested by @IvanSanchez looks like an elegant solution. If you can't use the plugin, the following might work for you:

CSS style:

.u-turn-icon {
   transform-origin: center;
}

Javascript:

map.on("zoomstart", function(ev) {
  let icons = document.getElementsByClassName("u-turn-icon");
  for(let icon of icons) {
    icon.style.visibility = "hidden";
  }
});

map.on("zoomend", function(ev){
  let icons = document.getElementsByClassName("u-turn-icon");
  for(let icon of icons) {
    icon.style.transform += " rotate(20deg)";
    icon.style.visibility = "";
  }
});

map.fire("zoomend");

This code simply resets the rotation of each u-turn icon every time the map is zoomed. The icon is hidden at the start of the zoom and revealed at the end, so you don't notice it rotating. A zoomend event is triggered manually to set the icon to the correct rotation before the map has been zoomed.

Mickimickie answered 19/1, 2019 at 21:50 Comment(1)
thanks. the plugin is easy to use. And your second solution is also easy to understand.Gainly

© 2022 - 2024 — McMap. All rights reserved.