4

Is it possible in to pan the map to the marker onClick regarding the popup height?

Currently, the popup disappears behind the map's mask. I'm looking for a solution, to fit both into the map, the marker and the popup (like adding some top padding).

featureLayer.on('click', function(e) {
   var latLng = e.layer.getLatLng();
   map.panTo(latLng);
});

mapbox small map with cut popup

mate64
  • 9,876
  • 17
  • 64
  • 96
  • Is your zoom level and popup fixed for every marker? If so, seems like you could just add some fixed unit of latitude before you panTo. – geografa Jul 30 '14 at 00:02
  • DO you have an example of this somewhere? Mapbox generally moves the map to fit the overlay – Jonathan Crowe Jul 30 '14 at 06:15

2 Answers2

3

I have found a native solution.

You need add the parameter keepInView to the bindPopup() command.

layer.bindPopup('<p>Hello</p>', {keepInView: true});

Documentation

mate64
  • 9,876
  • 17
  • 64
  • 96
  • 1
    From the documentation, won't this mean that you cannot scroll the map away from the popup altogether, also long after opening? – flup Aug 05 '14 at 18:50
1

Way late on answering this question, but I came across it so others might too. I was having a similar issue and Dan Mandle answered with this bit of code on a similar question:

map.on('popupopen', function(e) {
var px = map.project(e.popup._latlng); // find the pixel location on the map where the popup anchor is
px.y -= e.popup._container.clientHeight/2 // find the height of the popup container, divide by 2, subtract from the Y axis of marker location
map.panTo(map.unproject(px),{animate: true}); // pan to new center

});

This code worked great for me, and still allows for panning the map once the popup is open, unlike using keepInView.

Community
  • 1
  • 1
Tipster
  • 233
  • 2
  • 10
  • 1
    This sounds like exactly what I was looking for, thanks for the idea, nice to have this project/unproject out of the box : ) This method also works with Mapbox GL JS which is the preferred SDK now, and the keepinview/autopan feature is not implemented in this one, so must use the projection thingy if the default popup anchoring is not good for you. – seekingtheoptimal Jul 16 '20 at 22:27
  • lol but just noticed panBy accepts pixel coordinates for offset, so, it's easier and even works with pitch whatsoever :D – seekingtheoptimal Jul 18 '20 at 20:51
  • although if you are looking at the map in perspective, panBy() will not give the same result as expected, even if you calc your paddings/offsets, because of the pitch, your distances are not gonna be the same, as your popup will not be in the same angle as the plane of the map. Therefore some more complicated calculations are needed to have the correct amount of panBy offset to achieve the same results as when you are looking the map from above : ( – seekingtheoptimal Jul 18 '20 at 21:08