使用OpenLayers Map作为Angular服务



我想知道你是否知道一种方法,可以在Angular中使用一个服务来创建一个OpenLayers地图,并将该服务传递给其他组件,并根据这些组件之间的交互更新地图。以下是我的方法。我没有在屏幕上看到地图,但是,当我记录它时,正在创建map对象。

dashboard-map-service

import { Injectable } from '@angular/core';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
@Injectable({
providedIn: 'root'
})
export class DashboardMapService {
map: Map;
constructor() {
this.map = new Map({
view: new View({
center: [16400413.444439406, -5295269.033843756],
zoom: 12,
minZoom: 10,
}),
layers: [
new TileLayer({
source: new OSM(),
}),
]
})
}
returnMap(){
return this.map;
}
setMap(updatedMap: Map) {
this.map = updatedMap;
console.log("map", this.map)
}
}

add-location-component

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { Map } from 'ol';
import { DashboardMapService } from 'src/app/services/dashboard-map.service';
@Component({
selector: 'app-add-location',
templateUrl: './add-location.component.html',
styleUrls: ['./add-location.component.css']
})
export class AddLocationComponent implements OnInit, AfterViewInit {
refmap: Map;
constructor(private dashboardMap: DashboardMapService) {
this.refmap = dashboardMap.returnMap()
this.refmap.setTarget("add-location-map")

this.dashboardMap.setMap(this.refmap)
}
ngOnInit(): void {
}
ngAfterViewInit() {
}
}

我找到了答案,这与角生命周期挂钩有关。在ngAfterViewInit()中设置服务映射的目标和值就成功了。请看下面的代码:

ngAfterViewInit() {
this.refmap.setTarget("add-location-map")
this.dashboardMap.setMap(this.refmap)
}

相关内容

  • 没有找到相关文章

最新更新