8
votes

Can someone provide an explanation on how to use the Leaflet Marker Icon XY Coordinates listed here: http://leafletjs.com/examples/custom-icons/

Is lng/lat directly mapped to x/y? For example, sometimes in game engines, the Y pixel increases in value, but goes down the page. Here is it the same? I can't quite wrap my head around it.

1

1 Answers

15
votes

Not exactly sure what you mean by "Is lng/lat directly mapped to x/y?", but here are some explanations that should talk enough:

LatLng directions and XY directions (tile courtesy MapQuest)

As in most image manipulation software:

  • X increases from left to right
  • Y increases from top to bottom

When specifying iconAnchor and shadowAnchor for Leaflet custom icons, these directions still apply. Furthermore, like in most image software as well, the origin is the top left corner of your image.

iconAnchor directions

var myIcon = L.icon({
  iconUrl: 'path/to/image.png', // relative to your script location, or absolute
  iconSize: [25, 41], // [x, y] in pixels
  iconAnchor: [12, 41]
});

As explained in the doc, if you specify iconSize but not iconAnchor, Leaflet will assume your icon tip is at the center of your image and position it accordingly (same for shadow).

But if you do specify neither iconSize nor iconAnchor, Leaflet will position your icon image "as is", i.e. as if its tip was its top left corner. Then you can apply a className option and define it in CSS with negative left and top margins to re-position your image.

var myIcon = L.icon({
  iconUrl: 'path/to/image.png',
  // iconSize: [25, 41],
  // iconAnchor: [12, 41], // [x, y]
  className: 'custom-icon'
});
.custom-icon {
  margin-left: -12px; /* -x */
  margin-top: -41px; /* -y */
}

This usage might be more interesting when using a DivIcon, for which you may not know the size in advance, and use CSS transforms to position it.

As for the popupAnchor, it uses the icon tip as origin, so you will most likely specify a negative y value, so that the popup appears above the icon.

popupAnchor directions

popupAnchor: [1, -34] // [x, y]

Finally when adjusting your anchor values, a useful trick is to add a normal default marker at the exact same Lat/Lng location as the marker with your custom icon, so that you can compare both icon tip positions easily.