简体   繁体   中英

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM