Using OpenLayers Map as an Angular service

Viewed 35

I want to know if I you're aware of a way to use a service in Angular to create an OpenLayers map and pass that service to other components and update the map based on the interactions on those components. Below is my approach. I am not seeing the map on the screen, however, the Map object is being created when I log it.

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() {

  }

}
1 Answers

I found the answer, it was to do with the angular lifecycle hooks. Setting the target and value of the service map on ngAfterViewInit() did the trick. See the code below.

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