Angular应用中MapBox地图标记不显示及Logo恢复求助
Angular Mapbox 标记不显示+默认Logo恢复解决方案
问题根源
- 默认Logo/标注消失:初始化Map时设置了
attributionControl: false,直接禁用了Mapbox官方默认的Logo和版权控件,完全没必要手动创建替代元素。 - 标记不显示:大概率是地图初始化时机不对,加上容器
overflow: hidden样式遮挡了标记导致的。
修复步骤与代码修改
1. 恢复默认Mapbox Logo和版权标注
直接移除attributionControl: false配置(默认值为true),Mapbox会自动加载官方Logo和标准版权信息。
2. 修复标记不显示问题
- 将标记创建时机从
load事件改为ready事件,确保地图完全初始化后再添加标记 - 移除容器的
overflow: hidden样式,避免遮挡标记和默认控件
修改后的TS文件
import { Component, OnInit, Input, OnChanges, SimpleChanges, } from '@angular/core'; import { setMapboxAccessToken } from '@shared/services/mapbox.config'; import { MapboxService } from '@shared/services/mapbox.service'; import mapboxgl from 'mapbox-gl'; @Component({ selector: 'app-glassmorph-map-viewer', templateUrl: './glassmorph-map-viewer.component.html', styleUrls: ['./glassmorph-map-viewer.component.scss'], }) export class GlassmorphMapViewerComponent implements OnInit, OnChanges { @Input() width: string = '20rem'; @Input() height: string = '20rem'; @Input() latitude: number = 0; @Input() longitude: number = 0; map!: mapboxgl.Map; marker!: mapboxgl.Marker; constructor(private mapboxService: MapboxService) {} ngOnInit(): void { this.mapboxService.getToken().subscribe( (token) => { setMapboxAccessToken(token); this.initializeMap(); }, (error) => { console.error('Error fetching Mapbox token:', error); } ); } ngOnChanges(changes: SimpleChanges): void { if (changes['latitude'] || changes['longitude']) { this.updateMarkerPosition(); } } initializeMap(): void { // 移除attributionControl配置,使用默认的true this.map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v11', center: [this.longitude, this.latitude], zoom: 12, }); // 监听ready事件,确保地图完全初始化后再创建标记 this.map.on('ready', () => { this.createMarker(); }); this.updateMapSize(); } createMarker(): void { this.marker = new mapboxgl.Marker() .setLngLat([this.longitude, this.latitude]) .addTo(this.map); } updateMapSize(): void { const mapContainer = document.getElementById('map'); if (mapContainer) { mapContainer.style.width = this.width; mapContainer.style.height = this.height; this.map.resize(); } } updateMarkerPosition(): void { if (this.marker) { this.marker.setLngLat([this.longitude, this.latitude]); this.map.setCenter([this.longitude, this.latitude]); } } }
修改后的SCSS文件
.map-container { border-radius: 1rem; width: 100%; height: 100%; position: relative; // 移除overflow: hidden,避免遮挡标记和默认控件 }
HTML文件保持不变
<div id="map" class="map-container"></div> <ng-content></ng-content>
内容的提问来源于stack exchange,提问作者Yardi
相关产品推荐
相关产品推荐

