1

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

  }

}
Sarbraj Dulai
  • 180
  • 10
  • You must specify a `target` div in `new Map()` The div must have also have a size set by style or css. – Mike Jul 14 '22 at 10:55
  • @Mike, I did try both but it does not work. It works when everything is inside of the "add-location-component". – Sarbraj Dulai Jul 14 '22 at 10:57

1 Answers1

0

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)
  }
Sarbraj Dulai
  • 180
  • 10