首页 > 解决方案 > 如何在 Marker 中实现 mapbox 表达式?

问题描述

我怎样才能mapboxgl.Marker()像这样在里面添加 Mapbox 表达式:

"icon-size": ['interpolate', ['linear'], ['zoom'], 10, 1, 15, 0.5]

(我从这里复制了这个表达式:https ://stackoverflow.com/a/61036364/5220885 )

标签: javascriptmapboxmapbox-gl-js

解决方案


标记不支持表达式。它们是 HTML 元素,行为完全不同。

您将不得不按照以下方式伪造它:

  1. 将处理程序添加到地图的zoom事件中,以便您可以在地图放大和缩小时进行更新。
  2. 使用常规的旧 JavaScript 计算大小。
  3. 使用 CSS 应用该尺寸。

像这样的东西:

map.on('zoom', () => {
    const scalePercent = 1 + (map.getZoom() - 8)  * 0.4;
    const svgElement = marker.getElement().children[0];
    svgElement.style.transform = `scale(${scalePercent})`;
    svgElement.style.transformOrigin = 'bottom';
});

Codepen 在这里:https ://codepen.io/stevebennett/pen/MWyXjmR?editors=1001


推荐阅读