8

This is what I'm doing: Clicking a marker on the map to open a side panel and center the map on the marker. The side panel takes up 3/4 of the right side of the screen.

This is what I need to happen: Center the marker according to the 1/4 of the viewport that is left after the panel opens.

I can get the pixel coordinates of the marker and do the calculations of where it needs to translate to while the panel is animating open. The problem is that flyTo() only accepts LngLatLike objects and I cannot convert my pixel coordinates to latitude and longitude. Leaflet.js has a function called containerPointToLatLng() that came in handy before I switched to Mapbox GL.

Given the sofistication of Mapbox GL, despite its newness, I can only imagine this is a possibility. But how?

4

3 回答 3

16

projectunproject方法使很多这样的逻辑成为可能。如果您单击某个 lngLat,并且您想要定位地图,使该地理位置水平居中并位于 1/8 标记处,您可以:

  1. 获取地理位置并将其转换为像素位置project
  2. 将该像素位置向右移动 (1/2-1/8) = 4/8-1/8 = 3/8 = 0.375 * map._containerDimensions()[0],方法是将该数字加到它上面
  3. 将移动的像素位置转回地理位置unproject

或者,您也可以通过在调用中使用偏移选项来轻松完成此操作。flyTo

于 2016-12-17T00:42:10.013 回答
2

即使这是一个老问题,对于所有有相同要求的人(比如我),我在 mapbox 网站上找到了一个官方示例

于 2021-03-15T14:53:37.223 回答
0

我处于类似情况,只有我的侧导航菜单是 400 像素(相同的主体)。我遇到了同样的两个障碍:

  1. 为 flyto 函数计算从像素到 lat/lng 的校正
  2. 校正不同的缩放级别

@tmcw 的第一个答案做得非常好,但不幸的是,我的flyto 函数中的偏移选项不再可用。

它认为,为了获得不同缩放级别之间的线性比率,您需要根据文档划分 2 zoom1 :2 zoom2

完整示例:

// Desired zoom level at the end of flyTo
const zoomLevel = 16;
const zoomCorrection = Math.pow(2, this.map.getZoom()) / Math.pow(2, zoomLevel);

// Desired left shift/offset in px at the end of the flyTo. Use minus for right shift.
const leftShift = 200;


const lat = SelectedMarker.longitude;
const lng = SelectedMarker.latitude;
const coordinates = this.map.project([lat, lng]);
const offsetcoordinates = this.map.unproject([coordinates.x + (leftShift * zoomCorrection), coordinates.y]);

this.map.flyTo({
  animate: true,
  zoom: zoomLevel,
  center: [offsetcoordinates.lng, offsetcoordinates.lat],
});
于 2020-11-23T15:50:34.600 回答