Mapbox gl js - draw a car marker

前端 未结 2 1083
天涯浪人
天涯浪人 2021-01-27 11:30

I need to draw a car marker based on it\'s position. But, unlike all official examples, like this, I want size of my marker to be dependent on zoom level. And, I want it to have

相关标签:
2条回答
  • 2021-01-27 11:41

    The Mapbox API has evolved since 2018, and you can now do this in a slightly simpler way:

    First, extend the Marker class, to allow access to the private _rotation property:

    /* 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;
      }
    }
    

    Then simply call setRotation before updating the lat/lng:

    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);
    

    This code is TypeScript, but if you remove the typings, it will work in Vanilla JS as well.

    0 讨论(0)
  • 2021-01-27 11:42

    The Symbol layer 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/

    0 讨论(0)
提交回复
热议问题