Angular 19.1.7集成Google Maps JavaScript SDK交互时触发CORS错误问题求助
大家好,我现在在开发一个基于Angular 19.1.7的项目,需要集成Google Maps JavaScript SDK实现地图及绘图功能,目前遇到了一个很棘手的CORS问题,折腾了好久没找到原因,想请大家帮忙分析下。
我的实现方案
首先是在项目的index.html中引入Google Maps SDK脚本:
<script src="https://maps.googleapis.com/maps/api/js?key=MY_KEY_HERE&libraries=drawing" defer></script>
然后是地图组件的代码:
组件模板(HTML)
<div #mapContainer id="map"></div>
组件逻辑(TypeScript)
ngOnInit() { this.initMap() } initMap(): void { if (!window.google || !window.google.maps) { this.toaster.error('Google Maps API is not available. Please check your internet connection.'); return; } try { const mapOptions: any = { center: new (window.google.maps.LatLng as any)(40.730610, -73.935242), zoom: 12, }; // 创建地图实例 this.map = new (window.google.maps.Map as any)(this.mapContainer.nativeElement, mapOptions); this.initDrawingManager(); window.google.maps.event.addListener(this.map, 'click', (event: any) => { if (this.editMode === 'place-marker') { this.addMarkerAtPosition(event.latLng); } else if (this.editMode === 'none' && this.currentPolygonOverlay) { // 预留的空逻辑 } }); } catch (error) { this.toaster.error('Failed to initialize the map. Please refresh the page.'); } } initDrawingManager(): void { // 检查绘图库是否加载完成 if (!window.google.maps.drawing) { this.toaster.error('Map drawing tools are not available.'); return; } try { // 创建绘图管理器实例 this.drawingManager = new window.google.maps.drawing.DrawingManager({ drawingMode: null, // 初始为手型工具 drawingControl: true, drawingControlOptions: { position: window.google.maps.ControlPosition.TOP_CENTER, drawingModes: [ window.google.maps.drawing.OverlayType.POLYGON ] }, polygonOptions: { editable: true, draggable: true, strokeColor: '#ff0800ff', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#ca6f5fff', fillOpacity: 0.35 } }); // 初始状态隐藏绘图管理器 this.drawingManager.setMap(null); // 监听多边形绘制完成事件 window.google.maps.event.addListener( this.drawingManager, 'overlaycomplete', (event: any) => { this.drawingManager.setDrawingMode(null); const polygonId = `user-polygon-${this.userCreatedPolygons.length + 1}`; const polygonName = `User Polygon ${this.userCreatedPolygons.length + 1}`; const newPolygon = event.overlay; newPolygon.id = polygonId; this.userCreatedPolygons.push({ polygon: newPolygon, name: polygonName, color: '#00FF00' }); window.google.maps.event.addListener( newPolygon, 'mouseup', () => { this.getPolygonCoordinates(newPolygon, polygonName); } ); window.google.maps.event.addListener( newPolygon, 'click', () => { if (this.editMode === 'delete') { this.deletePolygon(newPolygon); } } ); this.getPolygonCoordinates(newPolygon, polygonName); this.savePolygonToDatabase(newPolygon); } ); } catch (error) { this.toaster.error('Failed to initialize drawing tools.'); } }
遇到的具体问题
页面首次加载时,地图能正常渲染,之前保存的标记、多边形也能正常显示。但只要和地图进行交互操作(比如缩放地图、点击打开街景),控制台就会抛出CORS相关的错误:
缩放地图时的错误:
Access to XMLHttpRequest at 'https://maps.googleapis.com/$rpc/google.internal.maps.mapsjs.v1.MapsJsInternalService/GetViewportInfo' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
打开街景时的错误:
Access to XMLHttpRequest at 'https://maps.googleapis.com/$rpc/google.internal.maps.mapsjs.v1.MapsJsInternalService/SingleImageSearch' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
POST https://maps.googleapis.com/$rpc/google.internal.maps.mapsjs.v1.MapsJsInternalService/SingleImageSearch net::ERR_FAILED
已完成的排查工作
- 我已经在Google Cloud控制台中,将该API密钥的应用限制设置为“无”,API限制也设置为“无”,确保没有权限规则导致的请求拦截
- 页面刷新时,
GetViewportInfo这个请求是能正常成功的,只有当主动和地图交互时才会触发CORS错误
有没有朋友遇到过类似的情况?或者知道可能的原因和解决方法?麻烦帮忙指点一下,非常感谢!
内容来源于stack exchange

