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

Develop a Java RESTful server with an Angular 5 client that utilizes POST and PUT syntax for communication

Currently, I am in the process of learning the HTTP REST/CRUD protocol in an attempt to establish communication between a Java RESTful servlet and an Angular5 client. I have successfully implemented the GET and DELETE functionalities, however, I am encount ...

What is the process of setting up Express as an API web server and integrating a custom document renderer as middleware?

I have developed a code generator and I want to be able to execute it on the server. The generator utilizes pure native ECMA6 JavaScript to render HTML markup, but it is transpiled to ES5 before runtime using Babel and WebPack. I am looking to use this on ...

Why does TypeScript require a generic type parameter when arguments have already been provided?

When I attempted to use the argument p to infer type P, TypeScript still prompted me to provide type P. Why is that? const numberStringConverter = <T extends string | number,P extends {x: any}>(p: P): T => { if(typeof p.x === 'string') ...

JavaScript: Creating an array of images from a directory

I've encountered a problem that has proven to be more complex than expected - I am struggling to find resources related to my specific question. My goal is to store 36 images from a folder on my computer into an array using Javascript. Below, you will ...

What could be causing my textarea-filling function to only be successful on the initial attempt?

Programming: function updateText() { $("body").on("click", ".update_text", function(event) { $(this).closest("form").find("textarea").text("updated text"); event.preventDefault(); }); } $(document).ready(function() { updateText(); }); H ...

Guide on invoking an Angular 1.5 component with a button press

Having just started learning Typescript, I'm struggling to figure out how to call my Angular component "summaryReport" on a button click. Here's a snippet of my code: Let's say I have a button that should call my component when clicked with ...

Mat-dialog not filtering JSON data properly due to filter buttons not combining logic

I'm currently working on developing a filter component, and I've encountered an issue. When I select both Buy it Now and Private Auction options, they function independently but not together. If an item has both Buy It Now and Private Auction ena ...

Understanding Node.js document object

Hey, I'm currently trying to execute a JavaScript function on the server side using node.js, but I've encountered an issue. The function relies on accessing hidden values within the returned HTML using the document DOM, however, the document obje ...

What is the process of dynamically loading CSS into an HTML document?

In my C# program, I am utilizing a web browser control and setting its HTML property programmatically by loading it from an HTML string variable. While this setup works almost perfectly, I have noticed that it loses the reference to the CSS file. I believe ...

Redirect the user to the shop page in Angular 2 if they already have

How can I set up a redirect for the User ID (this.authTokenService.currentUserData.id) if they are the owner of a shop? owner_id: number; private sub: any; ngOnInit() { this.sub = this.httpService.getShops().subscribe(params => { ...

What is the reason behind including a data string filled with a series of numbers accompanied by dashes in this ajax request?

I stumbled upon a website filled with engaging JavaScript games and was intrigued by how it saves high scores. The code snippet in question caught my attention: (new Request({ url: window.location.toString().split("#")[0], data: { ...

"Exploring the process of setting up a custom environment for ng serve in Angular

According to the angular 6 readme: ## Development server Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. Prior to version 6, I used to run this command for m ...

What is the process of sending an IPC message from a renderer to a webview within the same renderer

Is it possible to use Electron's ipcRenderer to send a message to a <webview> element? I attempted the following: var webview = document.getElementsByTagName("webview")[0]; webview.send("test", "testing"); as well as ipcRenderer.send("test" ...

Function for testing global variable stub in JavaScript

Currently, I am in the process of writing Unit tests for a React application. Within the page header, the tracking library 'mixpanel' is inserted between <script> tags as outlined in their documentation: . The documentation states that "Th ...

Saving information obtained through Angular subscribe into a variable

One of the services I have is called getWeather, which contains a method that communicates with an API using longitude and latitude parameters and then returns the response: import { Injectable } from '@angular/core'; import { HttpClient } from ...

Encountering the error message "Cannot GET /" in a NodeJS Express

I've been experimenting with various approaches to resolve this issue, ranging from app.use(express.static(__dirname + "public")) to res.render. It seems to function correctly in my terminal environment but fails when I try to access it locally. Can a ...

Optimal approach for vertically aligning elements in CSS

I'm looking to arrange my header ('Sail away today with Starboard Rentals.') and link buttons on top of each other. I want the navigation buttons to be positioned below the h1 on the lower half of the 'home-jumbo' div. What's ...

Retrieving the Vue component object while inside the FullCalendar object initialized within the component

When using Full Calendar with VueJS, I ran into a problem where I needed to open a custom modal when clicking on a time slot in the calendar. The issue was that I couldn't call a function outside of the Full Calendar object to handle this. This is bec ...

Issue with FullCalendar-vue and Typescript: the property 'getApi' is not recognized

Struggling to integrate FullCalendar-vue with Typescript, I encountered a problem when trying to access its API. This is how my calendar is set up: <FullCalendar ref="fullCalendar" :options="calendarOptions" style="width: 100%& ...

Obtaining an array element from mongoose at the corresponding index of the query

My Schema looks like this: const PublicationSchema = mongoose.Schema({ title: { type: String, required: true }, files:[{ contentType: String, data: Buffer, name: String }] }) I am attempting to re ...