When navigating to a new page, Ionic 3 and Open Layer 4 fail to display properly

Currently, I am in the process of developing a straightforward app using OpenLayers. For this project, I am utilizing Ionic 3 along with version "4.6.5" of OpenLayers as specified in my package.json: "openlayers": "^4.6.5",

Here is an overview of my page.ts file:

import { Component, ViewChild, Renderer, ElementRef } from '@angular/core';
    import { IonicPage,Platform } from 'ionic-angular';

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

    @IonicPage()
    @Component({
      selector: 'page-open-map',
      templateUrl: 'open-map.html'
    })

    export class OpenMapPage {

      map: OlMap;
      source: OlXYZ;
      layer: OlTileLayer;
      view: OlView;

      constructor(platform: Platform, public renderer: Renderer) {
        platform.ready().then(() => {
          console.log("Platform is ready");
          this.loadMap();
        })
      }

      loadMap() {
        this.source = new OlXYZ({
          // Map tiles sourced from Mapbox (Light)
          url: 'https://api.tiles.mapbox.com/v4/mapbox.light/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw'
        });

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

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

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

      }

    }

This is how my html file looks like:

 <ion-header>

      <ion-navbar>
        <ion-title>OpenMap</ion-title>
      </ion-navbar>

    </ion-header>

    <ion-content padding class="about">
      This is my incredibly fantastic About page.
     <div id="map" #map class="map" ></div>
    </ion-content>

After building the app, I noticed that the home page displays correctly but when transitioning to a new page, the map is missing. Can someone please assist me in identifying any errors in my code?

Your help is greatly appreciated!

Answer №1

To improve your HTML structure, consider placing the div element outside of the ion-content container.

Answer №2

Avoid using the platform.ready() function as your app should already be prepared when attempting to "open a new page".

Why not give this a try?

    constructor(public renderer: Renderer) {}

    ngAfterViewInit() { 
      this.loadMap()
    }

I recommend refraining from initializing anything in the constructor and instead moving it to the ngAfterViewInit() Lifecycle hooks. This way, you ensure that your target: 'map' or rather the

<div id="map" #map class="map" ></div>
element exists before instantiation.

The ngAfterViewInit event is fired after the DOM has finished loading completely

This approach could potentially resolve the issue you are facing

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

In the angular mat-chip-grid component, pressing the key combination of right Shift key and the letter M (<) on the keyboard functions as the Enter key

I have a code snippet that resembles this: https://material.angular.io/components/chips/overview ( Chips connected to an input field) <mat-form-field class="example-chip-list"> <mat-label>Favorite Fruits</mat-label> <mat ...

The art of effectively unit testing labels sourced from the Transloco API within an Angular setting

I've been using the Transloco API for a while now, but I'm having trouble getting it to work properly during unit testing. I've been following this blog post from ngneat on Unit testing with transloco However, even my simple test cases are ...

Exploring the concept of kleisli composition in TypeScript by combining Promise monad with functional programming techniques using fp-ts

Is there a way to combine two kleisli arrows (functions) f: A -> Promise B and g: B -> Promise C into h: A -> Promise C using the library fp-ts? Having experience with Haskell, I would formulate it as: How can I achieve the equivalent of the > ...

Issues arise during the deployment of Angular7 production build when passing through the Bitbucket package manager

I am working on a project to create a system that allows Angular components to be reused across multiple applications via BitBucket. Currently, I have the following setup: BitBucket Repo A - This repository stores the node module. The module is develope ...

Issue arises with the Prototype extension failing to function properly once an Angular application has been deployed

Utilizing a C# backend, I decided to incorporate a C# principle into the Angular frontend. Here is what I came up with: declare interface Date { addDays(days: number): Date; addYears(years: number): Date; isToday(): boolean; isSameDate(date ...

The username property in Angular is being read as undefined and causing an error

Currently, I am in the process of implementing a "Create" function to generate appointments and also include the User ID of the creator. To achieve this, I have set up models for "rendezvous" and "user." However, upon executing the project, I am encounteri ...

Data object constructor is not triggered during JSON parsing

Currently, I am retrieving data from a server and then parsing it into TypeScript classes. To incorporate inheritance in my classes, each class must be capable of reporting its type. Let me explain the process: Starting with the base class import { PageE ...

Downloading files using C# .NET Core WEB-API "proxy" functionality

I am utilizing an angular frontend with a PDF viewer along with a C# .NET core API. The .NET core API is responsible for downloading a file from an internal API and then passing it on to the angular PDF viewer as a proxy. While this setup works, the drawb ...

Search for specific item within an array of objects

Working on an Angular project, I am attempting to remove an object from an array. To achieve this, I need to filter the array and then update the storage (specifically, capacitor/storage) with the modified array. Here is my function: deleteArticle(id: str ...

What is the process for integrating custom TypeScript declaration files into the final build with rollup.js?

I am working on a project in Typescript where the files are built using rollup.js. Within my project, I have certain declaration files set up and I am curious if it is feasible to include these declaration files in the final built declaration file. Declar ...

Functions in Angular 4 that are triggered when a field is interacted with after clicking on a form

Looking for help with my form: <form [formGroup]="form" novalidate (ngSubmit)="onSubmit($event)"> I would like to trigger a specific function when any element of the form is clicked, such as: <form [formGroup]="form" novalidate (ngSubmit)="onSu ...

Strategies for handling uncaught promise rejections within a Promise catch block

I'm facing a challenge with handling errors in Promise functions that use reject. I want to catch these errors in the catch block of the Promise.all() call, but it results in an "Unhandled promise rejection" error. function errorFunc() { return ne ...

Can a lifecycle hook be interrupted in Angular 2?

Is there a way to prevent a Lifecycle Hook in angular2 from running when a specific variable becomes true? I have searched for information on this topic without success, but I believe it would be a great feature to have. ...

Ways to display all current users on a single page within an application

I have come across a project requirement where I need to display the number of active users on each page. I am considering various approaches but unsure of the best practice in these scenarios. Here are a few options I am considering: 1. Using SignalR 2. ...

"Enhance Your Angular 2 Module with a Secure Nested Dependency Injection Environment

I understand that Angular2's default DI Context strategy is to enhance an application-wide Dependency Injection Context. However, I want certain Injectables to not be accessible globally. Let me give you a specific example of what I am aiming for. T ...

Tips for resolving the issue of "unsupported platform for [email protected] : wanted"

After attempting to install angular-cli, I came across the following warning: unsupported platform for [email protected]: wanted"(OS windows 10). Being a beginner in Angular, I am looking for a simple solution to resolve this issue. Here is a scr ...

Is there a way to program a function that can automatically trigger or refresh an HTTP POST method?

How can I create a method in a distant component that will run a POST request when a button is clicked? I believe I need to use a service in this situation. It's not necessary for it(this.qwe) to be in the constructor, it's just an example... ...

Learn how to dynamically include files within the script tag using Angular4

Is there a way to dynamically include a remote file in a script tag using Angular4? For instance, if I have a file named https://rawgithub.com/eligrey/FileSaver.js/master/FileSaver.js as a query string parameter in the URL located in the address bar http: ...

Showing/hiding form field(s) when a mat-checkbox is checked in Angular

Looking to toggle the visibility of the search filter input field using a checkbox within the search filter button. Utilizing *ngIf to control the display, but encountering issues where it always reflects the boolean value of the last checked checkbox from ...

There is no available binary for the Chrome browser on your platform within the Docker container

While attempting to run Angular unit tests inside a Docker container, I encountered the following error message: 21 01 2021 01:51:10.057:INFO [launcher]: Launching browsers ChromeHeadless with concurrency unlimited 21 01 2021 01:51:10.063:INFO [launcher]: ...