How can I use an Openlayer 'overlay' inside Angular? I think the best way is via a @Viewchild construction. So, not via document.getElementById('overlay').
In the HTML file I have something like.
<div #overlayElement id="overlay" style="background-color: yellow; width: 20px; height: 20px; border-radius: 10px;">
<div #mapElement id="map" class="map"> </div>
The non-Angular solution is attaching the overlay logic to the Html 'overlay' element via the 'element: document.getElementById('overlay')'. That works.
UPDATE: thanks to @ zerO the logic is moved from the constructor to the ngOnInit().
In my Angular component I hoped to attach the overlay Html element with a viewtag "#overlayElement". In my component code I hoped to access it via a @Viewchild. I get a strange [Object object] error.
declare var ol: any;
@Component({
selector: 'app-tab4-controls',
templateUrl: './tab4-controls.component.html',
styleUrls: ['./tab4-controls.component.css']
})
export class Tab4ControlsComponent implements AfterViewInit, OnInit {
@ViewChild('mapElement') mapElement: ElementRef;
@ViewChild('overlayElement') overlayElement: ElementRef;
public map: any;
constructor() { }
ngOnInit(): void {
const layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
const interaction = new ol.interaction.DragRotateAndZoom();
const control = new ol.control.FullScreen();
const center = ol.proj.transform([-1.812, 52.443], 'EPSG:4326', 'EPSG:3857');
const overlay = new ol.Overlay({
position: center,
// element: document.getElementById('overlay') <== this works
element : this.overlayElement.nativeElement.id
});
const view = new ol.View({
center: center,
zoom: 6
});
this.map = new ol.Map({
layers: [layer],
interactions: [interaction],
controls: [control],
overlays: [overlay],
view: view
});
}
ngAfterViewInit() {
this.map.setTarget(this.mapElement.nativeElement.id);
}
I think constructor
might be too early to access it. Could you please try putting it in ngOnInit()
or ngAfterViewInit()
?