Leveraging the OpenLayers Map functionality within an Angular service

I am curious to learn if there is a way to utilize a service in Angular for creating an OpenLayers map and then passing that service to other components to update the map based on interactions within those components. I have outlined my approach below. Despite successfully logging the creation of the Map object, I am unable to see the map on the screen.

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

  }

}

Answer №1

After investigating further, I discovered that the solution lied within the utilization of Angular's lifecycle hooks. By properly setting both the target and value of the service map during ngAfterViewInit(), I was able to resolve the issue successfully. The code snippet below illustrates this implementation.

ngAfterViewInit() {
    this.newMap.setTarget("location-map")
    this.mapDisplay.setMap(this.newMap)
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to utilize the typescript module for detecting and managing typescript errors and warnings in your code?

Currently, I am experimenting with the typescript module to programmatically detect typescript errors. Below is a simplified version of what I have been working on: var ts=require('typescript') var file_content=` interface Message{ a:string ...

How is it possible that TypeScript does not provide a warning when a function is called with a different number of arguments than what is expected?

I am working on a vanilla JavaScript project in VS Code and have set up jsconfig.json. Here is an example of the code I am using: /** * @param {(arg: string) => void} nestedFunction */ function myFunction(nestedFunction) { // Some logic here } myFu ...

Encountering Error TS2411 when upgrading from Typescript version 1.0.0 to 1.1.0-1

After updating my TypeScript using npm install typescript -g, I have been encountering a recurring error during compilation. Although the compilation is successful, it's becoming tedious. cmd.exe /D /C C:/Users/Vado/AppData/Roaming/npm/tsc.cmd --sour ...

What is the reason behind Ramda having multiple curry functions in its source code, much like Redux having multiple compose functions?

There are _curry1, _curry2, _curry3, and _curryN functions within the depths of Ramda's source code This interesting pattern is also utilized in the redux compose function I find myself pondering: why did they choose this intricate pattern over a mo ...

Transferring data to a different module

I'm currently working on an Angular program where I am taking a user's input of a zip code and sending it to a function that then calls an API to convert it into latitude and longitude coordinates. Here is a snippet of the code: home.component.h ...

Error in Redux with TypeScript: "Argument of type 'AsyncThunkAction<any, number, {}>' is not compatible with parameter of type 'AnyAction'"

So I've been working on this dispatch function: const dispatch = useAppDispatch() const handleFetch = (e: React.MouseEvent<HTMLAnchorElement>) => { const target = e.target as Element dispatch(fetchCity(parseInt(ta ...

Using solely the directory to import index.ts

When attempting to import a module called index.ts from a directory by only specifying the directory name and not the module name itself, I encountered a TS2307 error stating "Cannot find module". Here is a snippet from ./src/main.ts: 'use strict&ap ...

Anguar 9 is experiencing issues with loading datatable pagination, search, and sorting functionalities

My problem lies in the pagination, search, and sorting functions not loading properly in my data table despite the data binding correctly. I have provided my html, component, and service files for reference. .html <table class="table table-striped ...

Jest - managing parent class methods during unit tests

The code snippet provided demonstrates a class called First extending TelemetryFramework with specific props and states, containing a method named getData. This method retrieves confidential data and logs telemetry information. However, running unit tests ...

Retrieve input from text field and showcase in angular 6 with material design components

Take a look at the output image . In the code below, I am displaying the contents of the messages array. How can I achieve the same functionality with a text box and button in an Angular environment? <mat-card class="example-card"> <mat-car ...

What is included in the final Angular build package selection?

Is there a tool available to track packages included in the final build of an Angular project? For instance: I am using the package "@angular/compiler" as a dependency in my package.json, but it is not a dev dependency. According to the Angular ...

The method for retrieving the value of a FormControlName in an array format for multiple select fields

Within this loop, I am iterating through the div multiple times and collecting all the select element values into a single array while replacing certain indexes. For instance, if I have four select elements in my HTML, there will be four select fields on ...

Ways to verify the presence of isBrowser in Angular 4

Previously, isBrowser from Angular Universal could be used to determine if your page was being rendered in a browser (allowing for usage of features like localStorage) or if it was being pre-rendered on the server side. However, it appears that angular2-u ...

What is the process of creating an instance of a class based on a string in Typescript?

Can someone please guide me on how to create an instance of a class based on a string in Nestjs and Typescript? After conducting some research, I attempted the following code but encountered an error where it says "WINDOWS is not defined." let paul:string ...

What is the best way to define a precise return type for a JSX Element?

Is it possible to define a function that returns a Button element and what would the correct return type of the function be? For example: Ex: const clickMeButton = (): Button => { return ( <Button> Click Me </Button& ...

Is there a way to replicate the tree structure of an array of objects into a different one while modifying the copied attributes?

Is there a way to replicate the tree structure of an array of objects to another one in TypeScript, with different or fewer attributes on the cloned version? Here's an example: [ { "name":"root_1", "extradata&qu ...

Stream in Node.js seems to have frozen

I am looking to develop a basic csv parser using the csv module and effectively handle errors when the file is missing. If I remove the sleep functions, the code successfully reaches the Finally statement (and produces an error output). What am I overloo ...

"Subscribing in interceptor doesn't seem to have any effect

I am currently facing an issue where I try to refresh a token using an API call, but the token does not get refreshed and the logs are not appearing as expected. In my code, I have implemented a timeout for testing purposes to trigger the token refresh and ...

The specific property 'splice' cannot be found within type 'T'

As I delve into working with TypeScript, an unexpected error arises: Property 'splice' does not exist on type 'T'. type Item = { name: string, body: string, imgOne: string, imgTwo: string, }[] // Another file contains this func ...

Angular Notification not visible

I have been attempting to display a notification after clicking a button using the angular-notifier library (version: 4.1.1). To accomplish this, I found guidance on a website called this. Despite following the instructions, the notification fails to app ...