Angular中如何将AGM地图插入jspdf生成的PDF?
问题概述
开发车辆追踪应用时,使用AGM地图展示车辆行驶轨迹,希望将地图导出到jspdf生成的PDF报告中。复用ng2-charts转canvas的方案时,出现以下错误:
ERROR TypeError: Cannot read properties of undefined (reading 'toDataURL') at component.SavePDF
错误原因
AGM地图是封装Google Maps的Angular组件,@ViewChild('map1')获取的是AGM组件的宿主div元素,而非地图渲染用的canvas。直接调用toDataURL()会报错,因为div元素没有该方法。
解决方案
1. 获取原生Google Maps实例
通过AGM的mapReady事件获取Google Maps原生对象:
模板修改:
<agm-map #map1 [zoom]="13" [latitude]="lat" [longitude]="lng" [fullscreenControl]="true" [mapTypeControl]="true" [fitBounds]="true" (mapReady)="onMapReady($event)"> <agm-polyline [visible]="true" [strokeWeight]="3" [strokeColor]="'#07b57a'"> <agm-polyline-point *ngFor="let coordinate of latlng; let i=index" [latitude]="coordinate[0]" [longitude]="coordinate[1]"></agm-polyline-point> </agm-polyline> </agm-map>
组件中保存地图实例:
import { Component } from '@angular/core'; import { jsPDF } from 'jspdf'; import html2canvas from 'html2canvas'; @Component({ // 组件元数据 }) export class VehicleTrackingComponent { private googleMap!: google.maps.Map; lat = 39.9042; // 示例纬度 lng = 116.4074; // 示例经度 latlng = [[39.9042, 116.4074], [39.9142, 116.4174]]; // 示例轨迹坐标 onMapReady(map: google.maps.Map) { this.googleMap = map; } }
2. 使用html2canvas将地图转为图片
安装html2canvas:
npm install html2canvas
在保存PDF的方法中,将地图容器转为canvas后导出:
async savePDF() { if (!this.googleMap) return; const mapContainer = this.googleMap.getDiv(); // 将地图容器转为canvas const canvas = await html2canvas(mapContainer, { useCORS: true, // 解决地图瓦片跨域问题 scale: 2, // 提升导出图片清晰度 logging: false // 关闭日志输出 }); const imgData = canvas.toDataURL('image/png'); const doc = new jsPDF('p', 'mm', 'a4'); // 调整图片位置和尺寸适配A4纸 doc.addImage(imgData, 'PNG', 20, 20, 170, 120); // 添加其他报告内容 doc.text('车辆行驶轨迹报告', 20, 15); doc.save('vehicle-tracking-report.pdf'); }
3. 关键注意事项
- 跨域处理:Google Maps瓦片存在跨域问题,必须设置
useCORS: true,同时确保项目允许跨域资源访问 - 渲染时机:需等待地图完全加载完成后再调用导出方法,可通过监听
tilesloaded事件确保渲染完成:onMapReady(map: google.maps.Map) { this.googleMap = map; map.addListener('tilesloaded', () => { console.log('地图加载完成'); // 可在此触发导出逻辑 }); } - 尺寸适配:根据PDF页面尺寸调整
addImage的参数(x, y, width, height),避免图片超出页面范围
内容的提问来源于stack exchange,提问作者Nooh Ahamad
相关产品推荐
相关产品推荐

