1

Does anybody know: can I use an angular component as the Mapbox custom control? I need to add a few buttons on the map, but I see I have to pass an HTML element.

1 Answers1

0

I did this using https://stackoverflow.com/a/54561421/12302484. I've made the class that implements the IControl interface. Then returned the component from the onAdd method resolved by dynamic component service.

map.component.ts:

private configureControls(): void {
    this.map.dragRotate.disable();
    this.map.touchZoomRotate.disableRotation();
    this.map.addControl(new mapboxgl.NavigationControl({ showCompass: false }));
    this.map.addControl(new CustomMapControls(this.dynamicComponentService));
}

custom-map-controls.ts:

export class CustomMapControls {
    private _container: HTMLElement;
    private _switchColorButton: HTMLElement;

    private map: mapboxgl.Map;
    private dynamicComponentService: DynamicComponentService;

    constructor(dynamicComponentService: DynamicComponentService) {
        this.dynamicComponentService = dynamicComponentService;
        this._container = document.createElement('div');
        this._container.classList.add('mapboxgl-ctrl', 'mapboxgl-ctrl-group');
    }

    getDefaultPosition(): any {
        return undefined;
    }

    onAdd(map: mapboxgl.Map): HTMLElement {
        this.map = map;
        this._container.appendChild(this.dynamicComponentService.injectComponent(MapColorSwitcherComponent));
        return this._container;
    }

    onRemove(map: mapboxgl.Map): any {
    }
}

result:

enter image description here