Zoom and center marker on click in leaflet

痴心易碎 提交于 2019-12-06 03:32:31

问题


I have a problem with my leaflet map. I have some markers on my map and when clicking on one, the marker is centered. Now I want when clicking on one marker it is not only centered but I want to zoom in to the marker. When I add this

    map.setZoom((16), {animate: true});

to

    map.on('popupopen', function(centerMarker) {
        var cM = map.project(centerMarker.popup._latlng);
        cM.y -= centerMarker.popup._container.clientHeight/2
        map.setZoom((16), {animate: true});
        map.panTo(map.unproject(cM),{animate: true});
    });

my code the centering doesn't really work because it zooms in but it doesn't center the marker. But all the other markers are centered if I'm in the expected zoom level (16). What can I do that the map zooms to the marker AND the marker is centered as well if I'm outside the zoom level 16? I'm quite new to leaflet and jquery...


回答1:


Instead of using setZoom and panTo, you can use single method setViewwith zoomoption.

map.on('popupopen', function(centerMarker) {
        var cM = map.project(centerMarker.popup._latlng);
        cM.y -= centerMarker.popup._container.clientHeight/2
        map.setView(map.unproject(cM),16, {animate: true});
    });



回答2:


What I did to center the icon popup on my screen was devide the clientHeight by zoom and it centered the popup:

mymap.on('popupopen', function(centerMarker) {
  const zoomLvl = 13;
  let cM = mymap.project(centerMarker.popup._latlng);

  cM.y -= centerMarker.popup._container.clientHeight / zoomLvl
  console.log(mymap.unproject(cM));
  mymap.setView(mymap.unproject(cM), zoomLvl, {animate: true});
});


来源:https://stackoverflow.com/questions/24527788/zoom-and-center-marker-on-click-in-leaflet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!