指南
如何在 {Capacitor} 中使用 Native Map
使用@capgo/capacitor-native-map
Android上使用Google Maps、iOS上使用Apple MapKit、Web上使用Google Maps JS,仅需一个用于标记、摄像头、形状、聚类和事件的TypeScriptAPI
安装
bun add @capgo/capacitor-native-map
bunx cap sync
此插件暴露的内容
create:在DOM元素中嵌入地图,或者toBack: true:在透明的HTML后面显示地图。updateLayout:调整和重新定位原生地图(CSS像素)。setCamera/fitBounds:控制摄像头和视图。addMarker/addMarkers/removeMarker:添加支持点击和拖拽的标记。enableClustering:将密集的标记集分组。enableCurrentLocation:在允许的情况下显示用户位置点。- :多边形、多边线、圆形和瓦片层(根据平台不同)。
示例使用
嵌入式地图
import { NativeMap } from '@capgo/capacitor-native-map';
const map = await NativeMap.create({
id: 'main-map',
element: document.getElementById('map')!,
apiKey: 'YOUR_GOOGLE_MAPS_API_KEY',
config: {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
},
});
map.setOnMapClickListener((e) => console.log(e.latitude, e.longitude));
// In a framework component, call `await map.destroy()` from your teardown/cleanup hook.
背景地图
const map = await NativeMap.create({
id: 'stores-map',
toBack: true,
apiKey: 'YOUR_GOOGLE_MAPS_API_KEY',
config: {
center: { lat: 40.7128, lng: -74.006 },
zoom: 11,
x: 0,
y: 0,
width: window.innerWidth,
height: window.innerHeight,
},
});
await map.updateLayout({
x: 0,
y: 0,
width: window.innerWidth,
height: window.innerHeight,
});
Wrap HUD 部分 data-map-overlay (参见入门指南) 因此,覆盖层 CSS 可以启用点击事件;透明区域将手势传递给地图。
完整参考
- GitHub: https://github.com/Cap-go/capacitor-native-map/
- 文档:/docs/plugins/native-map/