lifeson
lifeson

Reputation: 171

bind marker to map center using leaflet

I normally use google maps and use this to bind a crosshair icon to the center of the map

    var image = {
        url: 'images/site/crosshair.png',
        size: new google.maps.Size(32, 32),
        origin: new google.maps.Point(0,0),
        anchor: new google.maps.Point(16, 16)
    };

    var xhr = new google.maps.Marker({
        map: map,
        icon: image
    });
    xhr.bindTo('position', map, 'center');

How do I replicate this using leaflet.js? I have this which sets the icon on the center but it doesn't update as the map is dragged or zoomed

//create crosshair icon
var crosshair = L.icon({
  iconUrl: 'img/site/crosshair.png',
  iconSize: [32, 32],
  iconAnchor:[16,37]
});

L.marker(map.getCenter(), {icon: crosshair}).addTo(map);

Hope you can help

Upvotes: 2

Views: 1153

Answers (1)

YaFred
YaFred

Reputation: 10008

You have to listen to move events of your map and reposition the marker.

map.on('move', function(e) {
  marker.setLatLng(map.getCenter());
});

See this example

Note: apparently, leaflet does the job better than googlemaps api. See example.

Upvotes: 4

Related Questions