如何使用capacitor-google-map插件打开InfoWindow?
使用Capacitor Google Maps插件实现Marker点击显示InfoWindow
实现步骤
- 创建Marker时绑定自定义数据:添加Marker时通过
callbackData字段传入需要展示的信息,点击Marker时该数据会随回调返回。 - 监听Marker点击并触发InfoWindow:在点击回调中,利用返回的
markerId和callbackData调用插件的showInfoWindow方法展示弹窗。
完整代码示例
import { GoogleMap } from '@capacitor/google-maps'; import { environment } from '../environments/environment'; import { Component, ElementRef, ViewChild } from '@angular/core'; @Component({ template: ` <capacitor-google-map #map></capacitor-google-map> <button (click)="createMap()">Create Map</button> `, styles: [ ` capacitor-google-map { display: inline-block; width: 275px; height: 400px; } `, ], }) export class MyMap { @ViewChild('map') mapRef: ElementRef<HTMLElement>; newMap: GoogleMap; async createMap() { this.newMap = await GoogleMap.create({ id: 'my-cool-map', element: this.mapRef.nativeElement, apiKey: environment.apiKey, config: { center: { lat: 33.6, lng: -117.9, }, zoom: 8, }, }); // 添加携带自定义数据的Marker await this.newMap.addMarker({ coordinate: { lat: 33.6, lng: -117.9 }, callbackData: { name: '测试点位', detail: '这是Marker绑定的自定义详情内容' }, }); // 监听Marker点击事件 this.newMap.setOnMarkerClickListener((val) => { const { markerId, callbackData } = val; // 组装InfoWindow的HTML内容 const infoContent = `<h4>${callbackData.name}</h4><p>${callbackData.detail}</p>`; // 调用插件方法显示InfoWindow this.newMap.showInfoWindow({ markerId, content: infoContent, }); }); } }
关键细节说明
callbackData字段:支持传入任意格式的自定义数据,点击Marker时会完整返回,用于动态生成弹窗内容。showInfoWindow方法:必须传入目标Marker的markerId,content参数支持HTML格式,可自由定制弹窗样式。- 如需关闭弹窗,直接调用
this.newMap.hideInfoWindow()即可,无需额外参数。
内容的提问来源于stack exchange,提问作者Christophe Chenel
相关产品推荐
相关产品推荐

