如何在Angular中使用Openlayer的“覆盖”?我认为最好的方法是通过@Viewchild构造。因此,不是通过document.getElementById('overlay')。
在HTML文件中,我有类似的内容。
<div #overlayElement id="overlay" style="background-color: yellow; width: 20px; height: 20px; border-radius: 10px;">
<div #mapElement id="map" class="map"> </div>
非角度解决方案是通过'element:document.getElementById('overlay')'将覆盖逻辑附加到Html的“ overlay”元素。这样可行。
更新:由于@ zerO,逻辑从构造函数移至ngOnInit()。
在我的Angular组件中,我希望将覆盖的HTML元素附加到视图标签“ #overlayElement”。在我的组件代码中,我希望通过@Viewchild访问它。我收到一个奇怪的[Object object]错误。
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);
}
答案 0 :(得分:2)
我认为constructor
可能还为时过早。您可以尝试将其放入ngOnInit()
或ngAfterViewInit()
吗?