Mapbox gl js - 绘制汽车标记

Mapbox gl js - draw a car marker

我需要根据它的位置画一个汽车标记。但是,与 this 等所有官方示例不同,我希望标记的大小取决于缩放级别。而且,我希望它也有航向——我需要根据汽车的航向旋转它。使用 Mapbox GL JS 是否可行,如何实现?

符号层https://www.mapbox.com/mapbox-gl-js/style-spec#layers-symbol is best suited for this, see this example https://www.mapbox.com/mapbox-gl-js/example/rotating-controllable-marker/

Mapbox API 自 2018 年以来不断发展,您现在可以通过更简单的方式来实现:

首先,扩展标记 class,以允许访问私有 _rotation 属性:

/* eslint-disable */
import { Marker, MarkerOptions } from 'mapbox-gl';

export class RotatedMarker extends Marker {
  constructor(options?: MarkerOptions) {
    super(options);
  }

  /**
   * Set the element's rotation angle.
   * @param angle Angle in degrees
   */
  setRotation(angle: number): this {
    // @ts-ignore
    this._rotation = angle;
    return this;
  }
}

然后在更新 lat/lng:

之前简单地调用 setRotation
const myMarker = new RotatedMarker({
  element: someDivYouMade,
  anchor: 'center',
  rotation: 123, // in degrees
  rotationAlignment: 'map',
});

// When you want to rotate your marker, call this (call both, I'm pretty sure the
// marker won't rotate by just calling setRotation alone.
myMarker.setRotation(cssHeading)
  .setLngLat(carPosition);

此代码是 TypeScript,但如果您删除输入,它也可以在 Vanilla JS 中运行。