Using Angular with Google Maps: Learn how to retrieve a list of markers from a map and implement onClick events for each one

I am currently using the AGM angular module for Angular 2+ to integrate the Google Map API.

In my project, I have a directive that displays waypoints as markers on the map using the Google Map Directions Service.

Now, I am looking for a way to handle the onClick event on each marker on the map and display tooltips based on the marker's position.

However, I am struggling to find a method to retrieve a list of markers from the map object. Unfortunately, there is no "getMarkers()" method available.

Since the markers were added to the map by google.maps.DirectionsRenderer from the Google Maps Directions service response, I do not have a list of existing markers at this point.

Below is the code snippet of my directive:

@Directive({
  selector: 'agm-map-directions'
})
export class DirectionsMapDirective implements OnChanges {
  @Input()
  private waypoints: Waypoint[];
  @Input()
  private origin: string;
  @Input()
  private destination: string;
  @Input()
  private optimizeWaypoints: boolean;
  @Input()
  private travelMode: string;

  constructor (private gmapsApi: GoogleMapsAPIWrapper) {}

  ngOnChanges(changes: SimpleChanges): void {
    this.renderDirections();
  }

  renderDirections() {
    this.gmapsApi.getNativeMap().then(map => {
      let directionsService = new google.maps.DirectionsService;
      let directionsDisplay = new google.maps.DirectionsRenderer;
      directionsDisplay.setMap(map);
      directionsService.route({
        origin:  this.origin,
        destination: this.destination,
        waypoints: this.waypoints,
        optimizeWaypoints: this.optimizeWaypoints,
        travelMode: this.travelMode
      }, function(response, status) {
        if (status === 'OK') {
          directionsDisplay.setDirections(response);
          //There I want to handle markers onClick event
        } else {
          window.alert('Directions request failed due to ' + status);
        }
      });
    });
  }
}

Here is my template:

<div id="map">
  <agm-map *ngIf="mapLoaded"
           style="height: 500px"
           [zoomControl]="false"
           [disableDefaultUI]="false"
           [disableDoubleClickZoom]="true"
           [streetViewControl]="false">
    <agm-map-directions
      [waypoints]="waypoints"
      [origin]="supplierInfo.origin"
      [destination]="supplierInfo.destination"
      [optimizeWaypoints]="true"
      [travelMode]="'DRIVING'"></agm-map-directions>
  </agm-map>
</div>

Is there a method to easily retrieve a list of markers from the map object?

Alternatively, are there any other solutions to achieve the same goal?

Answer №1

Regrettably, the previous solution did not work for my situation, possibly due to the presence of my directive, though I cannot be certain.

Nevertheless, I managed to find an alternative solution.

Within my directive, I incorporated the following:

directionsDisplay.setOptions( { suppressMarkers: true } );

Subsequently, the markers no longer display automatically. Instead, I manually add them from the response route, where I have access to all marker positions on the Map in LatLng format.

Here is an example of the code:

renderDirections() {
    this.gmapsApi.getNativeMap()
      .then(map => {
        let directionsService = new google.maps.DirectionsService;
        let directionsDisplay = new google.maps.DirectionsRenderer;
        directionsDisplay.setMap(map);
        directionsService.route({
          origin:  this.origin,
          destination: this.destination,
          waypoints: this.waypoints,
          optimizeWaypoints: this.optimizeWaypoints,
          travelMode: this.travelMode
        }, (response, status) => {
          if (status === 'OK') {
            directionsDisplay.setDirections(response);
            directionsDisplay.setOptions( { suppressMarkers: true } );
            let route = response.routes[0];
            this.mapService.addMarkersToMap(route, map);
          } else {
            window.alert('Directions request failed due to ' + status);
          }
        });
      });
  }

By manually adding markers, I am able to set OnClick listeners and include infoWindows with buttons.

  addMarker(location, map) {
    let marker = new google.maps.Marker({
      position: {
        lat: location.lat(),
        lng: location.lng()
      },
      map: map
    });

    marker.addListener('click',  () => {
      let infoWindow = new google.maps.InfoWindow({
        content: 'some HTML content'
      });
      infoWindow.open(map, marker);
    })
  }

Answer №2

 <agm-map [latitude]="latitude1" [longitude]="longitude1" [zoom]="zoom" [usePanning]='true'>
    <agm-marker *ngFor="let location of locations; let i = index" (markerClick)="showLocationDetails(location)" [latitude]="location.latitude" [longitude]="location.longitude"
        [label]="a">
        <agm-info-window>
            <strong>{{location.name}}</strong>
        </agm-info-window>
    </agm-marker>

This code snippet is used to display multiple markers on a map. We loop through an array of locations and display a marker for each one. When a marker is clicked, the showLocationDetails function is called to show the details of that location to the user.

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

connect a column from a separate array in pdfmake

In my current project, I am looking to link the values of an array that is different from the one present in the initial two columns. Is this achievable? (The number of partialPrice values aligns with the number of code entries). Despite several attempts ...

Creating an Angular production build without the need for devDependencies installed

I am currently in the process of setting up a Docker container for building my Angular app in production. I am using npm and I only want to include dependencies, not devDependencies. This is what I have so far: npm install --only=prod ng build project-na ...

Angular causing alignment issues for items not centered

I'm having trouble centering the contents of a div with my code. The properties I am applying don't seem to work. Any idea why this is happening? <div class='center'> <form (ngSubmit)="loginUser()" style="background: steel ...

<Click here to navigate to page 2> await whenClicked={navigation.navigate("page_2")} />

Issue with assigning a 'string' to a parameter in TypeScript while trying to navigate to another screen in React Native. Can anyone help with this error? This problem occurs when we want to navigate to another screen using TypeScript in React Na ...

Tips on accessing validator errors in Angular

Is there a way to extract the value from the 'minLength' validator error in order to use it in a message? This is my current HTML setup: <div class="mt-2" *ngIf="ngControl.control.errors?.minlength"> {{ &ap ...

How to bring in a module from another package in Angular 4

This is a fundamental query. As an individual just starting with Angular and npm, this may seem like a basic question for some. However, despite extensive research, I haven't been able to find a solution. Before embarking on a project, I want to cre ...

Tips for assigning multiple Angular2 variables in Jquery on change

I am having trouble assigning more than one variable in jQuery within Angular2. Here is my current code: jQuery('.source-select').on('change',(e) => this.updateForm.value.sources = jQuery(e.target).val().split('--')[0]); ...

Choosing a specific row in Angular 5

I'm completely new to Angular, so please bear with me :) I have a collection of user data that is presented in the following format: https://i.sstatic.net/5UAIP.png Below is my current HTML structure: EDIT - ADDED CRUD BUTTONS : <!--Add ...

Tips for leveraging angular CLI's async import feature with webpack

I've been attempting to utilize webpack's (2.2.1) async module loading as outlined in the documentation. In addition, I have explored various examples for reference. However, I keep encountering the error message Declaration or statement expecte ...

What seems to be the issue with the useState hook in my React application - is it not functioning as

Currently, I am engrossed in a project where I am crafting a Select component using a newfound design pattern. The execution looks flawless, but there seems to be an issue as the useState function doesn't seem to be functioning properly. As a newcomer ...

TypeORM's one-to-many relationship alters the primary entity once the relationship has been established

When working on my side project, I decided to implement a friend request system using NestJS + TypeORM for the backend. However, I encountered a peculiar issue where every time I tried to associate a Friend entity with a specific user, the target field of ...

Is there a way to display the input value from an on-screen keyboard in an Angular application?

https://i.sstatic.net/j76vM.pnghttps://i.sstatic.net/EQPZO.png I have included my code and output snippet below. Is there a better way to display the input value when clicking on the virtual keyboard? ...

An unexpected TypeScript error was encountered in the directory/node_modules/@antv/g6-core/lib/types/index.d.ts file at line 24, column 37. The expected type was

Upon attempting to launch the project post-cloning the repository from GitHub and installing dependencies using yarn install, I encountered an error. Updating react-scripts to the latest version and typescript to 4.1.2 did not resolve the issue. Node v: 1 ...

What is the process for configuring Angular to recognize my SSL certificates?

I'm having trouble getting my angular application to use the key and certificate I created. I placed both files in a directory named "ssl." However, when I run "ng serve" for the first time, Angular generates its own keys (it was mentioned in the ter ...

Tips on running methods consecutively within ngOnInit in Angular

I'm currently working on an ngoninit function that contains four methods. Two of these methods are responsible for retrieving data from the API, while the other two are intended to load this data when the page loads. ngOnInit(){ getname(); getsubjects ...

Guide for transferring the body of a table to a different component without disrupting the design aesthetics

In an attempt to reorganize my large table component, I decided to separate its body section into a new component. However, every time I try to do this, the styling of the table breaks (likely due to the new HTML structure in the code). I'm currently ...

The Angular 6 watcher fails to compile the imported less files within the main.less file

Currently, I am developing in Angular version 6 and utilizing Less for styling purposes. In previous Angular versions, I utilized the angular_cli.json file to include the main Less file, which functioned properly. Now, in the latest Angular 6 version, I ...

What is the best way to implement a dispatch function in TypeScript?

Despite my expectations, this code does not pass typechecking. Is there a way to ensure it is well typed in Typescript? const hh = { a: (_: { type: 'a' }) => '', b: (_: { type: 'b' }) => '', } as const; ex ...

Strategies for analyzing Authorize.net payment responses in Ionic and JavaScript

Despite numerous attempts, I am struggling to parse the response from the authorize.net payment gateway. Below is the primary response from authorize.net: "{"transactionResponse":{"responseCode":"1","authCode" ...

Utilizing Rxjs to transform an array of objects

My goal is to map an array of objects. Currently, I have the following code: return this.service.post(url, payload, this.httpOptions) .pipe( map((obj: any, index) => [({ ...obj, val1: obj[index].val1.id, v ...