danyolgiax
danyolgiax

Reputation: 13086

Reference a marker from outside AGM Google Map

I'm using AGM Google Map component. I added marker in template with *ngFor.

import {  Component,  NgModule} from '@angular/core';
import {  BrowserModule} from '@angular/platform-browser';
import {  AgmCoreModule} from '@agm/core';
import {  AgmJsMarkerClustererModule,  ClusterManager } from '@agm/js-marker-clusterer;

@Component({
  selector: 'my-app',
  styles: [`
    .agm-map-container {
       height: 300px;
     }
  `],
  template: `
   <agm-map #gm style="height: 300px" [latitude]="52.692868" [longitude]="7.834982">

    <agm-marker *ngFor="let m of markers; let i = index" (mouseOver)="onMouseOver(infoWindow,gm)" [latitude]="m.latitude" [longitude]="m.longitude">

            <agm-info-window [disableAutoPan]="false" #infoWindow>
               Test
            </agm-info-window>


    </agm-marker>

</agm-map>
<button type="button" (click)="onFocusMarker1($event)">Focus marker 1</button>
<button type="button" (click)="onFocusMarker2($event)">Focus marker 2</button>

`})
export class AppComponent {

  markers: Array<any>
  constructor(){

    this.markers=[{latitude:52.692868, longitude:7.834982},{latitude:52.992868, longitude:7.034982}]

  }

  onFocusMarker1(event){
    event.preventDefault();

    alert("How to take reference of first marker, centrer the map on it and open the info window?");
  }

  onFocusMarker2(event){
    event.preventDefault();

    alert("How to take reference of second marker, centrer the map on it and open the info window?");
  }

   onMouseOver(infoWindow, gm) {

        if (gm.lastOpen != null) {
            gm.lastOpen.close();
        }

        gm.lastOpen = infoWindow;

        infoWindow.open();
    }
}

Now I need to press a button outside the map and center the map on a marker and open its InfoWindow but I cannot find a method to take the marker reference to achieve this.

I create a Plunkr here

Upvotes: 4

Views: 1333

Answers (1)

Anytoe
Anytoe

Reputation: 1675

I have struggled with the same problem. Though I was not able to get a reference to the marker itself, I ended up going the declarative way and use AgmInfoWindow.isOpen See here.

<agm-marker *ngFor="let m of markers; let i = index" (mouseOver)="onMouseOver(infoWindow,gm)" [latitude]="m.latitude" [longitude]="m.longitude">
   <agm-info-window [disableAutoPan]="false" [isOpen]="m.isOpen" #infoWindow>
      Test
   </agm-info-window>
</agm-marker>

if you now click the button outside the map you would only need to set the marker of your choice to

this.markers[0].isOpen = true; // I strongly assume you have a more sophisticated way of selecting your marker

And the window will open!

Upvotes: 1

Related Questions