NoName
NoName

Reputation: 65

Button click inside Info window in google maps

I want to add a button in info window. How can I access my service's functions in angular 2?

Example:

import {Injectable} from 'angular2/core';

@Injectable()
export class MapService {

  private map: any;
  constructor() { }

  initialize(): void {
    this.map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(33.751222, 33.98131),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  }

  addMarker(): void {
    let marker = new google.maps.Marker({
        position: new google.maps.LatLng(33.751222, 33.98131),
        map: this.map
    });
    let infoWindow = new google.maps.InfoWindow({
      content: `<h6>Content</h6><button onclick="foo()">Click me</button>`
    });
    google.maps.event.addListener(marker, 'click', () => {
      infoWindow.open(this.map, marker);
    });
  }

  foo() {
    console.log('Clicked!');
  }

}

This example, obviously, doesn't work: "ReferenceError: foo is not defined". How can I make this button work?

Thanks!

Upvotes: 1

Views: 1687

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657148

foo is searched on the window object.

I would use the approach explained in

How do expose angular 2 methods publicly?

to get a method of your service called.

If it were a component or directive instead of a service I would rather use this approach https://stackoverflow.com/a/36832108/217408 but you can also register an event handler imperatively like window.addEventHandler('my-custom-event', onMyCustomEvent) so the 2nd approach would also work with your service.

Upvotes: 2

Related Questions