Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LeafletJS markers move on zoom

Tags:

map

leaflet

Using LeafletJS which is ace, well until now :P We don't have a JSON object or anything, so I am taking the values out of the HTML (title, latlng) and creating markers. Generally that works ok, however there is an issue with the plotting of them. When the map is really zoomed in they seem to be ok, but when you zoom out (like the map is initially), they are way off. They then move on zoom.

So, what am I doing wrong?

http://jsbin.com/edegox/1 http://jsbin.com/edegox/1/edit

Cheers Tom

like image 539
Leads Avatar asked Jul 26 '13 07:07

Leads


2 Answers

The solution to this is quite simple. Leads should have posted it.

when your markers are moving around your map it's because the map doesn't know the size of your marker and/or it doesn't know the point of your marker that marks the location.

your marker icon code might look like this:

var locationIcon = L.icon({iconUrl:'location_marker_icon.png'});

now, let's suppose your image is 24px wide and 36px tall. To keep your marker from moving around, you simply specify the size of the marker, and the "anchor point"...

var locationIcon = L.icon({
    iconUrl:'location_marker_icon.png',
    iconSize: [24,36],
    iconAnchor: [12,36]
});

This will make the center pixel on the bottom represent the exact lat/lng point you specified the marker for, and it will keep it anchored there!

like image 197
Jaimz Avatar answered Sep 27 '22 20:09

Jaimz


Given an icon that looks like this, with an overall size of 98px wide by 114px tall:

enter image description here

  • iconSize will be [98, 114]. This is the overall size of the icon.
  • Your iconAnchor will be [49, 114]. The icon anchors first numeral can be calculated by taking the first numeral in the iconSize and dividing by 2 (i.e., 98 ÷ 2 = 49)

If you wanted to use this icon example, your final code should look like this:

var locationIcon = L.icon({
  iconUrl:'location_marker_icon.png',
  iconSize: [98, 114],
  iconAnchor: [49, 114]
});

Here's a Gist example you can test with (I highlighted the lines in question) https://gist.github.com/anonymous/fe19008c911e1e6b6490#file-index-html-L38-L44

like image 41
Joshua Powell Avatar answered Sep 27 '22 21:09

Joshua Powell