写在最前

1. 前端集成

npm install maplibre-gl

<template>
  <div ref="mapContainer" class="maplibre-map"></div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import maplibregl from 'maplibre-gl'
import 'maplibre-gl/dist/maplibre-gl.css'

const mapContainer = ref<HTMLElement | null>(null)
let map: maplibregl.Map | null = null

onMounted(() => {
  if (!mapContainer.value) return

  // 初始化MapLibre GL地图
  map = new maplibregl.Map({
    container: mapContainer.value,
    style: 'https://demotiles.maplibre.org/style.json', // MapLibre官方演示样式
    center: [116.3974, 39.9087], // 北京天安门坐标 [经度, 纬度]
    zoom: 12, // 初始缩放级别
    pitch: 0, // 倾斜角度
    bearing: 0, // 旋转角度
    antialias: true // 抗锯齿
  })

  // 添加导航控制器
  map.addControl(new maplibregl.NavigationControl(), 'top-right')

  // 添加比例尺
  map.addControl(new maplibregl.ScaleControl({
    maxWidth: 100,
    unit: 'metric'
  }), 'bottom-left')

  // 添加全屏控制器
  map.addControl(new maplibregl.FullscreenControl(), 'top-right')

  // 添加地理定位控制器
  map.addControl(new maplibregl.GeolocateControl({
    positionOptions: {
      enableHighAccuracy: true
    },
    trackUserLocation: true
  }), 'top-right')

  // 地图加载完成后的回调
  map.on('load', () => {
    console.log('MapLibre地图加载完成')
    
    // 可以在这里添加自定义图层、数据源等
    addDemoMarker()
  })

  // 地图点击事件
  map.on('click', (e) => {
    console.log('点击位置:', e.lngLat)
  })
})

// 添加示例标记点
const addDemoMarker = () => {
  if (!map) return

  // 创建一个标记
  const marker = new maplibregl.Marker({ color: '#FF0000' })
    .setLngLat([116.3974, 39.9087])
    .setPopup(
      new maplibregl.Popup({ offset: 25 })
        .setHTML('<h3>天安门</h3><p>北京市中心</p>')
    )
    .addTo(map)
}

// 组件卸载时清理地图实例
onUnmounted(() => {
  if (map) {
    map.remove()
    map = null
  }
})

// 暴露地图实例供外部使用
defineExpose({
  getMap: () => map
})
</script>

<style scoped>
.maplibre-map {
  width: 100%;
  height: 100%;
  position: relative;
}

/* 自定义地图控件样式 */
:deep(.maplibregl-ctrl-group) {
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.15);
}

:deep(.maplibregl-ctrl-group button) {
  width: 30px;
  height: 30px;
}

/* 自定义Popup样式 */
:deep(.maplibregl-popup-content) {
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

:deep(.maplibregl-popup-content h3) {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

:deep(.maplibregl-popup-content p) {
  margin: 0;
  font-size: 14px;
  color: #666;
}

/* 自定义标记样式 */
:deep(.maplibregl-marker) {
  cursor: pointer;
}
</style>

写在最后