No class defined for OpenLayers map

A little green in the world of angular (and javascript in general). Here's some code I'm working with:

import {Injectable, OnInit} from '@angular/core';


import OlMap from 'ol/map';
import OSM from 'ol/source/osm'
import OlXYZ from 'ol/source/xyz';
import OlTileLayer from 'ol/layer/tile';
import OlView from 'ol/view';
import OlProj from 'ol/proj';

@Injectable()
export class MapService {
    public  map: OlMap;
    private _source: OlXYZ;
    private _layer: OlTileLayer;
    private _view: OlView;


    constructor() { }

    /**
     * Function initializes the map
     * @returns {} Object of map
     */
    initMap() {
        this._source = new OSM({
        });

        this._layer = new OlTileLayer({
            source: this._source
        });

        this._view = new OlView({
            center: OlProj.fromLonLat([6.661594, 50.433237]),
            zoom: 10,
        });

        this.map = new OlMap({
            target: 'map',
            layers: [this._layer],
            view: this._view
        });

        this.map.on("moveend", function () {
            console.log(this.map);
        })
    }
}

The issue lies within the final line. I want to log the map object on moveend event (triggered when a user drags and releases the map), but for some reason, 'this.map' appears as undefined in the console. Despite this, other method calls on 'this.map' work just fine upon mouse button release.

I suspect it may be Javascript-related, possibly related to local or global object references, etc.

Any assistance would be greatly appreciated.

NOTE: The initMap() method is invoked in the map component like so:

ngOnInit() {
    this.map = this.mapService.initMap();

    console.log(this.mapService.map);
}

(The console.log returns the expected '_ol_map' object without any issues)

Answer №1

The distinction lies between using function () {} and () => {}.

  • In function () {}, the reference of "this" pertains to the caller of the function, which in this case is "OlMap".
  • In () => {}, the reference of "this" is set at the point of creation, leading back to "MapService".

It's important to note that this.map is not defined within OlMap.

To resolve this issue, a simple fix involves replacing function() with () => in the this.map.on() method call.

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

How can I retrieve data from a script tag in an ASP.NET MVC application?

I'm struggling to figure out how to properly access parameters in a jQuery call. Here is what I currently have: // Controller code public ActionResult Offer() { ... ViewData["max"] = max; ViewData["min"] = min; ... return View(paginatedOffers ...

What is the best way to incorporate features into an HTML email?

Is there a method to integrate basic web interactions like clicking on buttons and displaying confirmation messages directly within HTML emails, without triggering the opening of a new browser window? We are looking for a way to allow users to easily clic ...

jEditable: sending TinyMCE data back to textarea

Hey, I've got a mix of TinyMCE jQuery plugin and Jeditable on a textarea. What happens is, when the editable element is clicked it turns into a TinyMCE iframe. Now, my challenge is to get the content from the iframe back to the textarea using tinymce. ...

Problem with Jquery Sticky Navigation

I've been struggling to understand this issue and can't seem to find any help. http://fiddle.jshell.net/DQgkE/7/show/ The user experience is currently a bit glitchy, but what I would like is: 1) When scrolling down the page, I want the Sticky ...

Ways to optimize angular performance by minimizing unnecessary data binding:NSUTF8B

When comparing the performance of rendering a list using Angular versus other libraries like Handlebars, I noticed about a 10x decrease in speed. In my case, the table does not need to update dynamically when the model changes. If necessary, I can simply ...

Ensuring the size of the description box remains constant during window resizing in a fancy and

When resizing the window, I noticed that the description box next to the pop-up image in fancybox does not adjust its size accordingly. The image reduces in size but the description box remains the same. Is there a way to make the description box resize al ...

JavaScript - Insert a new key and value into an Object

Within my function, I have a forEach loop to create an Object: Please execute the code snippet: angular.module('myApp', []).controller('myCntl', function($scope) { $scope.t = ''; var input = "a,b,c,d,e,r \n1,1,1 ...

Exploring the Integration of SOAP Services with Angular 2

Can anyone provide guidance or direct me to some online resources for integrating a SOAP service with my Angular 2 application? Due to the nature of this legacy app, using REST is not an option currently. Thanks in advance! ...

Is there a way to emphasize a particular day on the calendar obtained from the URL?

I have implemented FullCalendar functionality to enable users to select a specific date, retrieve data from a database, and then reload the page with that data. The page is updated with the selected date in the URL. However, when the page reloads, althoug ...

Use the find() method in Vue.js to locate and correct this value

console.log(this.tiles.find(this.findStart)) When using the following code snippet: findStart: function (value) { var x = 5, y = 10; return value.x === x && value.y === y }, The expected results are returned. However, when su ...

Having trouble with data binding in Angular?

Problem: When deleting the first row and adding a second row, the value of the first row is being replaced by the value of the second row. I have created a plunker to demonstrate the issue I am encountering here To reproduce the issue, follow these steps ...

The Node.js script started by systemd is unable to connect with the SVN repository

Running on Ubuntu, I have a Nodejs script that acts as an HTTP server (using Express) and when a specific POST is made to the server, it logs in to SVN and executes an svn info command using the code below: svn_info = ["info", server, "--xml", "--non-inte ...

How can the '+' symbol affect the function "url(" + imageUrl + ")"?

I was looking at some jQuery code on a website and came across a line that confused me. What exactly does the + sign and spaces do in "url(" + imageUrl + ")"? I am new to jQuery and JavaScript. <!DOCTYPE html> <html lang="en"> <he ...

aria-labelledby attribute fails to work properly with tab and arrow key navigation

I am a beginner in the world of ARIA accessibility. I have noticed that when I use the tab or left/right arrow keys, the screen reader NVDA reads certain elements as clickable, even though when I hover my mouse over them, they are read correctly. Currently ...

Optional parameter left unassigned is not automatically determined as undefined

Why is TypeScript not inferring the optional parameter in this function as undefined when it's omitted from the call? function fooFunc<T extends number | undefined>(param?: T){ let x: T extends undefined ? null : T x = param ?? null as any ...

I possess a pair of items that require merging together while combining any overlapping key values in their properties

I have a scenario where I need to merge two objects and concatenate strings if they have the same key. obj1 = { name: 'John', address: 'Cairo' } obj2 = { num : '1', address: 'Egypt' } After merging, the r ...

What is the best way to define several mapped types in TypeScript?

Imagine you have the following lines of TypeScript code: type fruit = "apple" | "banana" | "pear" type color = "red" | "yellow" | "green" You want to define a type that includes a numeric propert ...

Tips for automatically breaking or paginating HTML in order to ensure that the resulting PDF mirrors the paginated HTML layout

I'm looking to implement a feature that automatically breaks or paginates HTML content in order to ensure that the resulting PDF matches the appearance of the original HTML. Requirement: If HTML content exceeds the size of an A4 paper, it should be s ...

Step-by-step guide to creating a perforated container:

I'm putting together a step-by-step guide on how to navigate through my app for the first time. Imagine a pop-up that explains how to use a specific button During the tutorial, I envision a darkened background with a highlighted circle around the bu ...

Unable to update state object with action

In my Vue application, I have a product list and form. When the product list is displayed, it triggers a request to my REST API which then populates the results in a Pinia store object called products. This process works smoothly and the products are succe ...