Interactive feature on Google Maps information window allowing navigation to page's functions

Working on an Angular2 / Ionic 2 mobile App, I am utilizing the google maps JS API to display markers on a map. Upon clicking a marker, an information window pops up containing text and a button that triggers a function when clicked. If this function simply logs data to the console, everything functions as expected.

However, I seem to be encountering a scope-related issue. When attempting to access any page function or call NavController to navigate to another page upon clicking the button, it fails.

addInfoWindow(marker, origContent){

    let infoWindow = new google.maps.InfoWindow();

    var content = document.createElement('div');
    content.innerHTML = (origContent);
    var button = content.appendChild(document.createElement('input'));
    button.type = 'button';
    button.id = 'showMoreButton';
    button.value = 'show more';
    google.maps.event.addDomListener(button, 'click', function () {
      request();
      // This successfully calls the "request()" method upon button click
    });

    google.maps.event.addListener(marker, 'click', () => {
      infoWindow.setContent(content);
    });


    function request() {

      this.navCtrl.push(RequestPage);
      // However, this does not work due to scoping issues. I am unable to access my page's methods or components.
    }

  }

Any suggestions on how I can overcome this obstacle and gain access to NavController? I've tried various approaches, including NgZone, but with no success...

Answer №1

Discovering the solution was surprisingly simple. By using "bind", I am able to access a function of my page with ease:

button.addEventListener('click', this.request.bind(this, variable1));
// This line calls the function "request(variable1)"

Here is the full context:

addInfoWindow(marker, origContent){
    let infoWindow = new google.maps.InfoWindow();

    var content = document.createElement('div');
    content.innerHTML = (origContent);
    var button = content.appendChild(document.createElement('input'));
    button.type = 'button';
    button.id = 'showMoreButton';
    button.value = 'show more';
    button.addEventListener('click', this.request.bind(this, resultsOneUser));

    google.maps.event.addListener(marker, 'click', () => {
      infoWindow.setContent(content);
    });
  }

function request() {
   this.navCtrl.push(RequestPage);
 }

Answer №2

Incorporating Ionic/Capacitor and Angular, I encountered the need to attach a click event to a custom button on a Google map that wasn't a marker or an infoWindow.

After spending more time than expected searching for a solution, I finally discovered a method that worked for me and resolved my issue.

button.addEventListener('click', this.request.bind(this, resultsOneUser));

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

Injecting services with an abstract class is a common practice in Angular library modules

In my development workflow, I have established an Angular Component Library that I deploy using NPM (via Nexus) to various similar projects. This library includes a PageComponent, which contains a FooterComponent and a NavbarComponent. Within the NavbarCom ...

Issue with IntersectionObserver not detecting intersection when the root element is specified

I am encountering an issue with my IntersectionObserver that is observing an img. It works perfectly when the root is set to null (viewport). However, as soon as I change the root element to another img, the observer fails to detect the intersection betwee ...

Navigating through JSON data that has been returned

When I use AJAX (jQuery) to query my database, the data I receive back is causing some difficulties. While searching for a solution, I came across similar issues posted by others who pointed out that the PHP code (specifically how data is stored in the arr ...

Are items placed into an array passed by reference or by value?

When working with custom Objects in an Angular context, I define two objects "a" and "b" using an interface. These are created as class attributes along with an empty array of these objects. public a: CustomObj; public b: CustomObj; public array: ...

Steps to retrieve the primary key associated with a duplicate entry error (1062) in MySQL using the Knex.js library

Testing out the database by sending values from an HTML form has been successful so far. Unique inserts and good connections are working well. However, intentionally sending a duplicate username for testing purposes results in an error message - which is e ...

Inoperative due to disability

Issue with Disabling Inputs: [disabled] = true [disabled] = "isDisabled" -----ts > ( isDisabled=true) Standard HTML disabler disable also not functioning properly [attr.disabled] = true [attr.disabled] = "isDisabled" -----ts > ( isDisabled=true) I am a ...

serving files using express.static

I have set up express.static to serve multiple static files: app.use("/assets", express.static(process.cwd() + "/build/assets")); Most of the time, it works as expected. However, in certain cases (especially when downloading many files at once), some fil ...

Sorting the Czech alphabet with the help of Tablesorter

Utilizing the tablesorter characterEquivalents extension as outlined in this documentation. I have created a similar extension for Czech characters, but the sorting is not functioning correctly for certain characters - like \u017d $.extend( $.tables ...

Issue encountered while trying to download Jade through npm (npm install -g jade)

I am having trouble downloading jade via npm on my Mac (Yosemite). After downloading node and updating npm, I tried to install jade but encountered a series of errors that I cannot resolve. Even attempting to use sudo did not help, as it only displayed s ...

Uncover the value type of a key in TypeScript without using a discriminated union

I want to implement a type map that ensures the type of an object's value for a specific key is determined by the value of another key. For example: type CurrencyValue = { code: string; value: number; }; type FieldMap = { text: string; curren ...

"The interconnection between NetBeans, jQuery, and AJAX is

My issue is with a Netbeans 7.4 (also tried 7.3) project involving PHP and JavaScript where breakpoints do not work in jQuery ajax loaded pages that contain included JavaScript. I have no problem with PHP or top-level JavaScript, but for example: In index ...

Sync JSON object modifications with the DOM using jQuery (or potentially other libraries)

I am working on developing a web application that would be able to update the HTML elements based on changes in a JSON object. For instance, I have an unordered list with data attributes: <ul data-id="elements"> <li data-id="01">Element 01< ...

How to show the raw image content-type using Vue.js

When retrieving an image from a REST API through an HTTP GET with a request body, I have successfully verified the returned content using node.js and chai.js: expect(res).to.have.header('Content-Type', 'image/jpeg'); expect ...

How can I set up multiselect values in AngularJS ui-select?

Solution: Success! I managed to resolve the issue by implementing this solution and creating a customized build of the ui-select. Hopefully, this fix will be incorporated into the official master branch soon! Issue Is there a way to set up a select elem ...

How to Delete an Added Image from a Dialog Title in jQuery

I've tried multiple solutions from various sources, but I'm still struggling to remove an image from a dialog. Whenever I attempt to do so, I end up with multiple images instead of just one. It's important to note that I only want the image ...

Error encountered due to an unhandled promise rejection of type

I am currently using async/await to execute a query to the database and receive the result. However, I encountered an error in the browser console that says: Unhandled promise rejection TypeError: "games is undefined" In my code, there are two function ...

Getting the Correct Nested Type in TypeScript Conditional Types for Iterables

In my quest to create a type called GoodNestedIterableType, I aim to transform something from Iterable<Iterable<A>> to just A. To illustrate, let's consider the following code snippet: const arr = [ [1, 2, 3], [4, 5, 6], ] type GoodN ...

Change a space-separated string containing coordinates into an array of JavaScript objects

Here is a string separated by spaces: const coordinates = "42.44492,75.637764 42.445503,75.64534 42.433681,75.6604" Now, we want to convert it into an array of objects: const coordinatesArray = [ { lat: 42.44492, lng: 75.637764 }, { lat: 42.4455 ...

What could be causing the elements in my array to appear as undefined?

https://i.stack.imgur.com/ze1tx.png I'm stuck trying to understand why I can't extract data from the array. const usedPlatformLog: Date[] = [] users.forEach(el => { usedPlatformLog.push(el.lastUsed) }) console.log(usedPlatformLog) // disp ...

What is the process for fetching a user's role using Strapi?

Could someone assist me in retrieving the role associated with a specific user using strapi? I have tried running this query but have been unable to retrieve the role. https://i.stack.imgur.com/3SI2l.png If anyone has any insights or advice, it would be ...