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
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.
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/