What is the best way to show an alert() when a user clicks on a marker in Google Maps?

My current setup:view image description ...

google.maps.event.addListener(marker,'click',function() {

  this.map.setZoom(15);
  this.map.setCenter(marker.getPosition());
  console.log('hello world');
  this.presentAlert(); // ERROR core.js:9110 ERROR TypeError: 
  //this.presentAlert is not a function

});

...

What I'm aiming for:view image description

Expanded version of my code: ...

 public addMarker(lat: number, lng: number) {
    //let latLng = new google.maps.LatLng(lat, lng);
    let latLng = new google.maps.LatLng(21.576, -158.271); // favorite hiking 
    // spot

    let marker = new google.maps.Marker({
      map: this.map,
      animation: google.maps.Animation.DROP,
      position: latLng
    });

    this.markers.push(marker); // gotta catch 'em all

    google.maps.event.addListener(marker,'click',function() {

      this.map.setZoom(15);
      this.map.setCenter(marker.getPosition());
      console.log('hello world');
      this.presentAlert(); // ERROR core.js:9110 ERROR TypeError: 
      // this.presentAlert is not a function

    });

  }

presentAlert() {
        this.alertCtrl.create({
          header: 'Alert',
          subHeader: 'Subtitle',
          message: 'This is an alert message.',
          buttons: ['OK']
        }).then(alert=> {
          alert.present();
        });

      }

...

I've attempted various solutions, but this approach seems most logical to me. Can anyone provide assistance? Thank you in advance.

Answer №1

Utilize a local variable instead of referencing this

It is important to use a local variable because the value of this can change depending on the context in which it is being used.

public addMarker(lat: number, lng: number) {
  ...

  let self = this;

  google.maps.event.addListener(marker, 'click', function() {
    ...

    self.presentAlert();
  });

}

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

Manipulating CSS rules using JavaScript/jQuery

My goal is to create a function that generates a grid based on table data. While the function itself seems to be working, I am encountering an issue where the classes applied are not resulting in any style changes. Below is a snippet of my function: $(doc ...

Sending a response in the catch block based on conditions

I am currently working on finding the correct method to handle a potential bad Fetch response. My goal is to immediately send a 500 response and halt the code execution if the Fetch response is not okay. However, if the response is acceptable, I need to ...

extract element from a string with the help of jquery

When using AJAX to request HTML from a page, the process involves sending a request like this: function getHTML() { //set ajax call var options = { url: '/Controller', type: 'GET', d ...

What is the best way to retrieve the value of the hidden fields once the radio button has been selected?

I am currently attempting to retrieve the value of the hidden input fields each time a radio button is clicked. The code provided shows a single div structure, but there are multiple divs with the same structure. While I have been able to successfully ca ...

A guide on testing the onClick() function and useState hooks with jest and enzyme

I'm relatively new to testing with jest and enzyme, and I'm facing challenges when it comes to covering functions like onClick(), useState variables, and useEffect(). Can someone who has experience in similar scenarios provide some guidance on ho ...

What are the steps to resolve the "undefined cannot read property push" error in Node.js?

While attempting to learn Nodejs, I created a simple app. However, when I run "nodemon index.js" in the command prompt, I encountered the following error: TypeError: Cannot read property 'push' of undefined The app crashed and is now waiting for ...

Develop a custom npm package with dependencies stored locally and add it to a different package during installation

I have developed three unique custom modules. getcorrespondence-1.0.0.tgz getrediscache-1.0.0.tgz setrediscache-1.0.0.tgz These custom node modules were created using the command npm pack. The module getcorrespondence-1.0.0.tgz has dependencies on two o ...

I am attempting to link my Firebase real-time database with Cloud Firestore, but I am encountering import errors in the process

I am currently working on enhancing the online functionality of my chat app by implementing a presence system using Firebase Realtime Database. Here is the code snippet that I have created for this purpose: db refers to Firestore and dbt refers to the Rea ...

Using Webpack to transfer a function to the front-end

I am currently delving into the world of webpack and attempting to set up a basic integration. Within my file script.js, I have included some essential functions: scripts.js export foo = () => { console.log('foo') } export bar = () => ...

What is the best way to streamline the if statement in JavaScript?

Here is the given code snippet: public noArtistBeingEdited(): boolean { if (this.isFirstNameBeingEdited()) { return false; } if (this.isLastNameBeingEditable()) { return false; } return true; } What are some ways to ma ...

The function Jquery.html() seems to be malfunctioning in IE7, however, innerHTML is working correctly in the

One of my recent implementations involves populating a div using an ajax response. Take a look at the code snippet below for better understanding: jQuery.ajax({ type: 'POST', url: url, dataType: 'json', data:data, s ...

Display the same data point on a Google Map from two different rows of a database

I'm looking to display multiple values for profFName and profLName on a map with just one point showing this information. If I have (2) pID connected to the same marker, I want it to show both profFName and profLName on a single point. Currently, it ...

Removing the Yellow Highlight on Input Field Following Email Autocomplete in Chrome

My username-password form is styled and working perfectly, but there's an issue that arises when I log in multiple times. Chrome automatically fills in my email, turning the username textbox yellow. It doesn't seem to happen with Firefox or Safar ...

What is the best way to automatically adjust the size of this HTML Menu to match the width of its

I am in the process of converting a Drupal 6 theme to Drupal 7 and I'm encountering some difficulties with this particular section. Below is the HTML code snippet: <ul id="nav" class=" scaling-active scaling-ready"> <li><a href="/demos ...

What is the process for creating a linked TreeNode in the Ant tree design?

After completing a tree design utilizing Ant Design, I encountered an issue where certain nodes within the tree needed to act as links. Despite my attempts to directly assign links, they were not functioning properly. array.map((node) => { if(node.t ...

Omit a certain td element from the querySelectorAll results

Greetings! I am currently working with an HTML table and I need to figure out how to exclude a specific td element from it, but I'm not sure how to go about it. Here's the HTML code: <table id="datatable-responsive" c ...

The contents of a Javascript array are not appearing within a div element

I have developed a program that reads JSON data related to a concert event. The JSON file consists of an object named global, which includes details about the band name and venue. Additionally, there is a tickets object that contains information on all ava ...

I am looking for a setup where a checkbox triggers the opening of the next accordion

I am encountering a problem with the bootstrap accordion feature. I am looking to have the first accordion nested inside a checkbox, so that when the checkbox is clicked, the next accordion automatically opens. If the checkbox is not clicked, the next ac ...

When a JSON response contains an array of objects with only one element, it is received as a single object

When sending a response from my resource as an array of objects, I encounter an issue where if the array only contains one element, the response is transformed into a single object instead of an array with one object, preventing me from looping through it. ...

When the function is called, it will return the global `this

Attempting to bind the user object as 'this' and default time as the first parameter utilizing the function.call method let user = { name:'rifat', txt (time, msg){ console.log('['+time+ '] '+ this.name+ &apo ...