0
votes

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 heading as well - I need to rotate it based on the car's heading. Is it possible with Mapbox GL JS, and how to do it?

2

2 Answers

1
votes

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.