0

Ich habe eine Map mit einem Marker und wenn ich auf den Marker klicke, soll der Name in der Toolbar angezeigt werden. Wenn ich auf "console.log" klicke, wird der korrekte Wert angezeigt, aber nichts wird in der Symbolleiste aktualisiert. Aber wenn ich auf den Marker klicke und den Tab ändere und zurückgehe, funktioniert es.Ionic 2 google maps marker click

import { Component, ViewChild, ElementRef } from '@angular/core'; 
import { NavController } from 'ionic-angular'; 
declare var google; 
@Component({ 
    selector: 'page-home', 
    templateUrl: 'home.html' 
}) 
export class HomePage { 
    @ViewChild('map') mapElement: ElementRef; 
    map: any; 
    name: string = ""; 
    constructor(public navCtrl: NavController) { 
    } 
    ionViewDidLoad() { 
    this.initializeMap(); 
    } 
    initializeMap() { 
    let letLng = new google.maps.LatLng(62.3908, 17.3069); 
    let mapOptions = { 
     center: letLng, 
     zoom: 7, 
     mapTypeId: google.maps.MapTypeId.HYBRID 
    } 
    this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions); 
    this.addMarker(); 
    } 
    addMarker() { 
    let marker = new google.maps.Marker({ 
     map: this.map, 
     animation: google.maps.Animation.DROP, 
     position: { lat: 62.3908, lng: 17.3069 }, 
     title: 'Kalle' 
    }) 
    let content = `<h1>Kalle</h1>`; 
    this.addInfoWindow(marker, content); 
    } 
    addInfoWindow(marker, content) { 
    let infoWindow = new google.maps.InfoWindow({ 
     content: content 
    }); 
    google.maps.event.addListener(marker, 'click',() => { 
     this.name = marker.title; 
     infoWindow.open(this.map, marker) 
    }) 
    } 
    change() { 
    this.name = "Patrik"; 
    } 
} 
<<<<<<<<<<<<<<<HTML>>>>>>>>>>>>>>>>>>>>< 
<ion-header> 
    <ion-navbar> 
    <ion-title>{{name}}</ion-title> 
    <button ion-button (click)="change()">Clcik</button> 
    </ion-navbar> 
</ion-header> 
<ion-content> 
<div #map id="map"></div> 
</ion-content> 

Antwort

2

Verwenden Sie die NgZone-API.

import {NgZone} from @angular/core 

//inject in constructor 
constructor(public navCtrl: NavController,private ngZOne:NgZone) {} 
//.... 

google.maps.event.addListener(marker, 'click',() => { 
    //Call run function to set the data within angular zone to trigger change detection. 
    this.ngZone.run(()=>{ 
    this.name = marker.title; 
    infoWindow.open(this.map, marker) 
    }); 
}) 

NgZone API.

+0

Süße, seit langer Zeit gesucht :) ty. Können Sie erklären, warum dies in diesem Fall passiert? – MrPY

+0

Ich habe Google Maps API nicht verwendet .. aber es sieht so aus, als ob die Änderungen außerhalb von Angulars Zone vorgenommen werden, wo es Änderungserkennung durchführt. https://blog.Thoughtram.io/angular/2016/01/22/understanding-zones.html –