天地图在Vue中的高级应用:自定义标点与测量工具开发指南

Vue集成天地图实现精准地理测量与标注功能实战 本文详细介绍了在Vue项目中集成天地图API,并实现测距、测面及精准坐标标注等核心功能的实战指南。通过动态加载API、封装工具方法及管理交互状态,开发者可以快速构建具备专业地理测量与标注能力的地图应用,提升GIS开发效率。 阅读详情

天地图在Vue中的高级应用:自定义标点与测量工具开发指南

当你的Vue项目需要集成地图功能,并且基础的地图展示已经无法满足需求时,下一步的进阶之路往往指向了交互与定制。天地图作为国内主流的地图服务之一,其API提供了丰富的底层能力,但如何将这些能力封装成用户体验流畅、功能强大且易于维护的Vue组件,则是区分普通开发者与高阶玩家的关键。这篇文章不会重复讲解如何引入天地图SDK或创建一个基础地图实例——这些内容随处可见。我们将直接切入核心,探讨如何从零构建一套高度自定义的标点系统和具备专业级精度的测量工具,并在这个过程中,解决那些官方文档未曾提及的实战难题。

想象这样一个场景:用户需要在地图上精确标注一批设备点位,每个点位的图标需要根据设备状态动态变化;同时,规划人员需要测量一片不规则区域的面积,并要求实时显示周长和面积,且测量过程支持撤销、重做。这不仅仅是调用几个API方法那么简单,它涉及到Vue响应式数据与地图状态的同步、自定义图标的性能优化、测量算法的精度控制,以及一套清晰的状态管理策略。本文将围绕这些高阶需求,为你拆解实现思路,并提供可直接复用的代码方案。

1. 构建可复用的自定义标点系统

基础的地图标点(Marker)功能,天地图API已经提供。但当我们面对成百上千个点位,且每个点位需要携带复杂业务数据、支持动态交互时,原生T.Marker类就显得力不从心了。我们的目标是创建一个SmartMarker组件,它能够与Vue的响应式系统深度集成。

1.1 设计响应式标点数据模型

首先,我们需要一个清晰的数据结构来定义标点。这个结构不仅要包含地理位置,还要承载业务属性和UI状态。

// types/marker.ts
export interface SmartMarkerOption {
  id: string | number; // 唯一标识
  lnglat: { lng: number; lat: number }; // 经纬度对象
  title?: string; // 标题,用于Tooltip
  content?: any; // 自定义业务数据
  icon?: MarkerIconConfig; // 图标配置
  draggable?: boolean; // 是否可拖拽
  visible?: boolean; // 是否可见
  zIndex?: number; // 层级
}

export interface MarkerIconConfig {
  url: string; // 图标地址(支持base64、svg、png等)
  size: [number, number]; // [width, height]
  anchor?: [number, number]; // 图标锚点,默认为图标中心
  className?: string; // 自定义CSS类名,用于高级样式控制
}

在Vue组件中,我们将使用一个响应式数组来管理所有标点。关键在于,当这个数组发生变化(增、删、改)时,地图上的标点需要同步更新,且性能要足够好。

<!-- components/SmartMarkerLayer.vue -->
<script setup lang="ts">
import { ref, watch, onUnmounted } from 'vue';
import type { SmartMarkerOption } from '../types/marker';

const props = defineProps<{
  mapInstance: any; // 传入已初始化的天地图实例
  markers: SmartMarkerOption[];
}>();

const markerInstances = new Map<string | number, any>(); // 存储天地图原生Marker实例

// 核心:监听markers数组变化,同步更新地图
watch(() => props.markers, (newMarkers, oldMarkers) => {
  // 实现高效的差异更新(Diff算法思路)
  updateMarkersOnMap(newMarkers, oldMarkers);
}, { deep: true });

const updateMarkersOnMap = (newList: SmartMarkerOption[], oldList: SmartMarkerOption[]) => {
  // 1. 找出需要删除的标点(存在于oldList,但不在newList中)
  const toRemove = oldList.filter(oldMarker => 
    !newList.some(newMarker => newMarker.id === oldMarker.id)
  );
  toRemove.forEach(marker => {
    const instance = markerInstances.get(marker.id);
    if (instance) {
      props.mapInstance.removeOverLay(instance);
      markerInstances.delete(marker.id);
    }
  });

  // 2. 找出需要更新或新增的标点
  newList.forEach(newMarker => {
    const oldMarker = oldList.find(m => m.id === newMarker.id);
    if (!oldMarker) {
      // 新增标点
      addMarkerToMap(newMarker);
    } else if (!isMarkerEqual(oldMarker, newMarker)) {
      // 更新现有标点(如位置、图标变化)
      updateMarkerOnMap(newMarker);
    }
  });
};

const addMarkerToMap = (option: SmartMarkerOption) => {
  const { T } = window;
  const icon = option.icon ? new T.Icon({
    iconUrl: option.icon.url,
    iconSize: new T.Point(...option.icon.size),
    iconAnchor: option.icon.anchor ? new T.Point(...option.icon.anchor) : undefined
  }) : undefined;

  const marker = new T.Marker(
    new T.LngLat(option.lnglat.lng, option.lnglat.lat),
    { icon, draggable: option.draggable, title: option.title }
  );

  // 绑定事件,并将事件抛给父组件
  marker.addEventListener('click', (e: any) => {
    emit('marker-click', { marker: option, nativeEvent: e });
  });

  props.mapInstance.addOverLay(marker);
  markerInstances.set(option.id, marker);
};
</script>

注意:在大量标点频繁更新的场景下,全量销毁再重建的性能开销是巨大的。上述updateMarkersOnMap函数实现了一个简单的差异更新策略,是保证流畅体验的关键。

1.2 实现动态图标与聚合渲染

当标点数量过多时,不仅渲染性能下降,用户体验也会变差(屏幕上一片密密麻麻的点)。动态图标和点聚合是两种有效的解决方案。

动态图标通常根据标点的某个业务属性(如状态、类型)来切换。我们可以预先定义一套图标映射规则。

// utils/icon-manager.js
const iconRegistry = {
  normal: { url: '/icons/marker-green.png', size: [32, 40] },
  warning: { url: '/icons/marker-yellow.png', size: [32, 40] },
  error: { url: '/icons/marker-red.png', size: [32, 40] },
  custom: (data) => ({ 
    url: `data:image/svg+xml;base64,${generateSVG(data)}`, 
    size: [40, 40] 
  })
};

// 在SmartMarkerLayer的更新逻辑中调用
const getIconConfig = (markerOption) => {
  const type = markerOption.content?.type;
  if (type && iconRegistry[type]) {
    return typeof iconRegistry[type] === 'function' 
      ? iconRegistry[type](markerOption.content)
      : iconRegistry[type];
  }
  return iconRegistry.normal;
};

点聚合(Cluster) 则是将一定距离范围内的多个点合并成一个图标显示,并显示数量。天地图API本身不直接提供聚合功能,但我们可以借助第三方库(如 leaflet.markercluster 的适配思路)或自己实现一个简化版。

实现聚合的核心步骤:

  1. 根据地图当前缩放级别和视野范围,将屏幕坐标相近的标点归为一组。
  2. 为每一组创建一个聚合点图标,图标上显示该组的点数。
  3. 当地图缩放时,重新计算分组并更新聚合图标。
// utils/cluster.js (简化示例)
export function createClusters(markers, map, zoom) {
  const gridSize = 100; // 像素网格大小,用于分组
  const clusters = [];
  const mapBounds = map.getBounds();

  // 将落在屏幕外的点过滤掉
  const visibleMarkers = markers.filter(m => mapBounds.containsPoint(m.lnglat));

  // 简单的网格聚类算法
  const grid = {};
  visibleMarkers.forEach(marker => {
    const pixelPoint = map.lngLatToContainerPoint(marker.lnglat);
    const gridX = Math.floor(pixelPoint.x / gridSize);
    const gridY = Math.floor(pixelPoint.y / gridSize);
    const gridKey = `${gridX}_${gridY}`;

    if (!grid[gridKey]) {
      grid[gridKey] = {
        count: 0,
        markers: [],
        centerPixel: { x: 0, y: 0 }
      };
    }
    grid[gridKey].count++;
    grid[gridKey].markers.push(marker);
    // 累加坐标,后续计算中心点
    grid[gridKey].centerPixel.x += pixelPoint.x;
    grid[gridKey].centerPixel.y += pixelPoint.y;
  });

  // 生成聚合点
  for (const key in grid) {
    const cluster = grid[key];
    const centerPixel = {
      x: cluster.centerPixel.x / cluster.count,
      y: cluster.centerPixel.y / cluster.count
    };
    const centerLngLat = map.containerPointToLngLat(centerPixel);
    
    clusters.push({
      lnglat: centerLngLat,
      count: cluster.count,
      childMarkers: cluster.markers
    });
  }

  return clusters;
}

在Vue组件中,我们需要监听地图的zoomchange和moveend事件,以触发重新聚合计算。

2. 开发高精度测量工具

测量距离和面积是地图应用的常见功能。虽然天地图提供了T.PolylineTool和T.PolygonTool,但它们在交互反馈、精度控制和数据导出方面往往不够灵活。我们将封装一个功能更全面的MeasurementTool组件。

2.1 封装交互式测量组件

这个组件需要提供三种测量模式:测距、测面、测点(坐标拾取),并且允许用户在测量过程中进行交互式调整。

首先,定义组件的状态和模式:

<!-- components/MeasurementTool.vue -->
<template>
  <div class="measurement-control">
    <el-radio-group v-model="activeMode" @change="handleModeChange">
      <el-radio-button label="none">无</el-radio-button>
      <el-radio-button label="distance">测距</el-radio-button>
      <el-radio-button label="area">测面</el-radio-button>
      <el-radio-button label="point">拾取</el-radio-button>
    </el-radio-group>
    
    <div v-if="measurementResult" class="result-panel">
      <h4>测量结果</h4>
      <p v-if="activeMode === 'distance'">距离: {{ measurementResult.distance }} 公里</p>
      <p v-if="activeMode === 'area'">
        面积: {{ measurementResult.area }} 平方公里<br>
        周长: {{ measurementResult.perimeter }} 公里
      </p>
      <p v-if="activeMode === 'point'">
        坐标: {{ measurementResult.lng.toFixed(6) }}, {{ measurementResult.lat.toFixed(6) }}
      </p>
      <el-button size="small" @click="clearMeasurement">清除</el-button>
      <el-button size="small" @click="exportResult">导出</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';

type MeasureMode = 'none' | 'distance' | 'area' | 'point';
const activeMode = ref<MeasureMode>('none');
const measurementResult = ref<any>(null);
const props = defineProps<{ mapInstance: any }>();

// 存储测量过程中的临时图形和点
let tempOverlays: any[] = [];
let points: any[] = [];
let isMeasuring = false;
</script>

2.2 实现测距与测面的核心算法

天地图工具类虽然方便,但有时我们需要更底层的控制,比如自定义测量线的样式、实时显示分段距离等。下面我们手动实现测距逻辑。

// 在MeasurementTool组件的setup中
const initDistanceMeasurement = () => {
  const { T } = window;
  const map = props.mapInstance;
  
  // 监听地图点击事件来添加点
  map.addEventListener('click', onMapClickForDistance);
  
  // 监听鼠标移动,实时绘制预览线
  map.addEventListener('mousemove', onMouseMoveForDistance);
};

const onMapClickForDistance = (e: any) => {
  const point = e.lnglat;
  points.push(point);
  
  // 绘制点标记
  const marker = new T.Marker(point, {
    icon: new T.Icon({
      iconUrl: '/icons/measure-point.png',
      iconSize: new T.Point(12, 12)
    })
  });
  props.mapInstance.addOverLay(marker);
  tempOverlays.push(marker);
  
  // 如果已有一个以上的点,绘制线段
  if (points.length >= 2) {
    const linePoints = points.slice(-2); // 取最后两个点
    const polyline = new T.Polyline(linePoints, {
      color: '#1890ff',
      weight: 3,
      opacity: 0.8,
      lineStyle: 'solid'
    });
    props.mapInstance.addOverLay(polyline);
    tempOverlays.push(polyline);
    
    // 计算并显示这段距离
    const distance = calculateDistance(linePoints[0], linePoints[1]);
    addDistanceLabel(linePoints[1], distance);
    
    // 更新总距离
    updateTotalDistance();
  }
};

// 核心距离计算函数(使用Haversine公式,考虑地球曲率)
const calculateDistance = (point1, point2) => {
  const { lng: lng1, lat: lat1 } = point1;
  const { lng: lng2, lat: lat2 } = point2;
  
  const R = 6371; // 地球半径,单位公里
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLng = (lng2 - lng1) * Math.PI / 180;
  const a = 
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
    Math.sin(dLng / 2) * Math.sin(dLng / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  const distance = R * c;
  
  return distance; // 单位:公里
};

对于面积测量,原理类似,但需要处理多边形闭合和面积计算。这里使用球面多边形面积算法,比平面投影算法精度更高,尤其适用于大范围测量。

const calculatePolygonArea = (points: any[]) => {
  if (points.length < 3) return 0;
  
  const R = 6371; // 地球半径,公里
  let area = 0;
  
  // 将经纬度转换为弧度
  const radPoints = points.map(p => ({
    lng: p.lng * Math.PI / 180,
    lat: p.lat * Math.PI / 180
  }));
  
  // 使用球面三角剖分法计算面积
  for (let i = 0; i < radPoints.length; i++) {
    const j = (i + 1) % radPoints.length;
    const p1 = radPoints[i];
    const p2 = radPoints[j];
    
    area += (p2.lng - p1.lng) * 
            (2 + Math.sin(p1.lat) + Math.sin(p2.lat));
  }
  
  area = Math.abs(area * R * R / 2);
  return area;
};

2.3 精度控制与坐标系处理

在实际项目中,测量精度常常被忽略,但这恰恰是专业工具与玩具工具的区别。影响精度的因素主要有两个:坐标采集精度和算法精度。

坐标采集精度:天地图地图点击事件返回的坐标是经过地图投影转换的,其精度受地图缩放级别影响。在高级别缩放下(如18级),精度可达亚米级;而在低级别下,误差可能达到几十米。如果你的应用对精度要求极高,可以考虑以下策略:

  1. 在测量模式下,自动将地图缩放到一个较高的级别(如15级以上)。
  2. 提供坐标输入框,允许用户直接输入高精度经纬度。
  3. 使用鼠标移动+键盘微调的组合方式进行精确定位。
// 键盘微调坐标的示例
const handleKeyDownForPrecision = (e: KeyboardEvent) => {
  if (!selectedPoint) return;
  
  const step = 0.00001; // 约等于1米
  switch(e.key) {
    case 'ArrowUp':
      selectedPoint.lat += step;
      break;
    case 'ArrowDown':
      selectedPoint.lat -= step;
      break;
    case 'ArrowLeft':
      selectedPoint.lng -= step;
      break;
    case 'ArrowRight':
      selectedPoint.lng += step;
      break;
  }
  updatePointOnMap(selectedPoint);
};

坐标系处理:天地图默认使用WGS84坐标系(EPSG:4326),但测量距离和面积时,我们实际上是在球面上计算。对于小范围测量(如城市内),使用平面近似算法误差不大;但对于跨区域或大范围测量,必须使用球面几何算法。上文提供的calculateDistance和calculatePolygonArea函数已经考虑了地球曲率。

此外,如果你的数据源使用其他坐标系(如GCJ-02、BD-09),需要在测量前进行坐标转换。建议在数据接入层统一处理,确保进入测量模块的坐标都是WGS84。

3. 状态管理与性能优化

当标点数量和测量复杂度增加时,应用性能可能成为瓶颈。合理的状态管理和优化策略至关重要。

3.1 使用Pinia进行集中状态管理

将地图状态、标点集合、测量结果等全局状态集中管理,可以使组件逻辑更清晰,也便于调试。

// stores/map-store.js
import { defineStore } from 'pinia';

export const useMapStore = defineStore('map', {
  state: () => ({
    mapInstance: null,
    markers: [], // SmartMarkerOption数组
    measurements: [], // 历史测量记录
    activeTool: null, // 当前激活的工具
    viewState: { center: [116.4, 39.9], zoom: 10 }
  }),
  
  actions: {
    addMarker(marker) {
      this.markers.push(marker);
      // 这里可以触发持久化或与后端同步
    },
    
    removeMarker(id) {
      this.markers = this.markers.filter(m => m.id !== id);
    },
    
    updateMarkerPosition(id, newLngLat) {
      const marker = this.markers.find(m => m.id === id);
      if (marker) {
        marker.lnglat = newLngLat;
      }
    },
    
    saveMeasurement(result) {
      this.measurements.push({
        ...result,
        id: Date.now(),
        createdAt: new Date().toISOString()
      });
    }
  },
  
  getters: {
    visibleMarkers: (state) => {
      return state.markers.filter(m => m.visible !== false);
    },
    
    markerCountByType: (state) => {
      const counts = {};
      state.markers.forEach(m => {
        const type = m.content?.type || 'unknown';
        counts[type] = (counts[type] || 0) + 1;
      });
      return counts;
    }
  }
});

在组件中使用:

<script setup>
import { useMapStore } from '@/stores/map-store';
import { storeToRefs } from 'pinia';

const mapStore = useMapStore();
const { visibleMarkers, markerCountByType } = storeToRefs(mapStore);

// 添加标点
const handleAddMarker = () => {
  mapStore.addMarker({
    id: `marker_${Date.now()}`,
    lnglat: { lng: 116.4, lat: 39.9 },
    content: { type: 'normal', name: '测试点' },
    icon: { url: '/icons/marker.png', size: [32, 40] }
  });
};
</script>

3.2 渲染性能优化技巧

  1. 虚拟滚动/视窗裁剪:当地图上有成千上万个标点时,即使使用聚合,初始化加载也可能很慢。我们可以实现一个简单的视窗裁剪:只渲染当前地图视野范围内的标点。
const getVisibleMarkers = (allMarkers, mapBounds) => {
  if (!mapBounds) return allMarkers;
  
  return allMarkers.filter(marker => {
    const point = new T.LngLat(marker.lnglat.lng, marker.lnglat.lat);
    return mapBounds.containsPoint(point);
  });
};

// 监听地图移动事件,更新可见标点
mapInstance.addEventListener('moveend', () => {
  const bounds = mapInstance.getBounds();
  const visible = getVisibleMarkers(allMarkers, bounds);
  updateMarkersOnMap(visible);
});
  1. 图标缓存:频繁创建T.Icon实例会影响性能。可以建立一个图标缓存池。
const iconCache = new Map();

const getCachedIcon = (iconConfig) => {
  const key = `${iconConfig.url}_${iconConfig.size.join('x')}`;
  if (!iconCache.has(key)) {
    const { T } = window;
    iconCache.set(key, new T.Icon({
      iconUrl: iconConfig.url,
      iconSize: new T.Point(...iconConfig.size)
    }));
  }
  return iconCache.get(key);
};
  1. 防抖与节流:地图事件(如mousemove、moveend)触发非常频繁。对处理函数进行防抖或节流处理,避免不必要的计算和渲染。
import { throttle } from 'lodash-es';

const throttledUpdate = throttle(() => {
  updateVisibleMarkers();
}, 200); // 200ms内最多执行一次

mapInstance.addEventListener('moveend', throttledUpdate);

4. 高级功能扩展与实战案例

掌握了基础框架后,我们可以进一步扩展功能,满足更复杂的业务场景。

4.1 标点连线与路径规划

有时用户需要将多个标点按顺序连接起来,形成一条路径。我们可以扩展SmartMarkerLayer,使其支持连线功能。

<!-- 在SmartMarkerLayer组件中添加 -->
<template>
  <div>
    <!-- 原有内容 -->
    <el-button @click="connectMarkers" v-if="selectedMarkerIds.length >= 2">
      连接选中点
    </el-button>
  </div>
</template>

<script setup>
const selectedMarkerIds = ref([]);
const polylines = ref([]); // 存储连线实例

const connectMarkers = () => {
  if (selectedMarkerIds.value.length < 2) return;
  
  // 按选中顺序获取坐标点
  const points = selectedMarkerIds.value.map(id => {
    const marker = props.markers.find(m => m.id === id);
    return new T.LngLat(marker.lnglat.lng, marker.lnglat.lat);
  });
  
  // 创建连线
  const polyline = new T.Polyline(points, {
    color: '#52c41a',
    weight: 4,
    opacity: 0.7,
    lineStyle: 'dashed' // 虚线样式
  });
  
  props.mapInstance.addOverLay(polyline);
  polylines.value.push(polyline);
  
  // 计算总路径长度
  const totalDistance = calculatePathDistance(points);
  console.log(`路径总长度: ${totalDistance.toFixed(2)}公里`);
};
</script>

4.2 测量结果的可视化导出

测量结果不仅要在屏幕上显示,还需要支持导出为多种格式,方便用户保存和分享。

// utils/export-utils.js
export function exportMeasurementAsGeoJSON(measurement) {
  const geojson = {
    type: "FeatureCollection",
    features: []
  };
  
  if (measurement.type === 'distance' && measurement.points) {
    geojson.features.push({
      type: "Feature",
      geometry: {
        type: "LineString",
        coordinates: measurement.points.map(p => [p.lng, p.lat])
      },
      properties: {
        distance_km: measurement.distance,
        measuredAt: measurement.timestamp
      }
    });
  }
  
  if (measurement.type === 'area' && measurement.polygon) {
    geojson.features.push({
      type: "Feature",
      geometry: {
        type: "Polygon",
        coordinates: [measurement.polygon.map(p => [p.lng, p.lat])]
      },
      properties: {
        area_sqkm: measurement.area,
        perimeter_km: measurement.perimeter
      }
    });
  }
  
  return JSON.stringify(geojson, null, 2);
}

export function exportAsImage(mapInstance, bounds) {
  // 使用html2canvas或类似库将地图区域导出为图片
  // 注意:需要处理天地图水印和版权信息
  return new Promise((resolve) => {
    const container = mapInstance.getContainer();
    const options = {
      useCORS: true, // 允许跨域图片
      backgroundColor: null,
      scale: 2 // 高清导出
    };
    
    // 这里需要引入html2canvas库
    // html2canvas(container, options).then(canvas => {
    //   resolve(canvas.toDataURL('image/png'));
    // });
  });
}

4.3 与后端API的集成实战

在实际项目中,标点数据通常来自后端API,测量结果也需要保存到服务器。这里展示一个完整的异步数据流示例。

// services/marker-service.js
import { useMapStore } from '@/stores/map-store';

export class MarkerService {
  constructor() {
    this.mapStore = useMapStore();
  }
  
  async fetchMarkersByBounds(bounds) {
    // bounds: { southwest: [lng, lat], northeast: [lng, lat] }
    try {
      const response = await axios.get('/api/markers/within-bounds', {
        params: {
          minLng: bounds.southwest[0],
          minLat: bounds.southwest[1],
          maxLng: bounds.northeast[0],
          maxLat: bounds.northeast[1]
        }
      });
      
      // 转换API数据为前端模型
      const markers = response.data.map(item => ({
        id: item.id,
        lnglat: { lng: item.longitude, lat: item.latitude },
        content: {
          type: item.device_type,
          status: item.status,
          lastUpdated: item.updated_at
        },
        icon: this.getIconByDeviceType(item.device_type, item.status)
      }));
      
      // 更新Pinia store
      this.mapStore.setMarkers(markers);
      
      return markers;
    } catch (error) {
      console.error('获取标点数据失败:', error);
      throw error;
    }
  }
  
  async saveMeasurement(measurementData) {
    const payload = {
      type: measurementData.type,
      geometry: measurementData.geometry, // GeoJSON格式
      properties: measurementData.properties,
      userId: getCurrentUserId()
    };
    
    const response = await axios.post('/api/measurements', payload);
    
    // 更新本地存储
    this.mapStore.saveMeasurement({
      ...measurementData,
      serverId: response.data.id
    });
    
    return response.data;
  }
  
  getIconByDeviceType(type, status) {
    // 图标映射逻辑
    const iconMap = {
      'camera': {
        'online': { url: '/icons/camera-green.png', size: [28, 36] },
        'offline': { url: '/icons/camera-gray.png', size: [28, 36] },
        'alarm': { url: '/icons/camera-red.png', size: [28, 36] }
      },
      'sensor': {
        'normal': { url: '/icons/sensor-blue.png', size: [24, 32] }
      }
    };
    
    return iconMap[type]?.[status] || { url: '/icons/default.png', size: [24, 32] };
  }
}

在Vue组件中使用该服务:

<script setup>
import { onMounted, watch } from 'vue';
import { MarkerService } from '@/services/marker-service';

const markerService = new MarkerService();
const mapStore = useMapStore();

// 当地图视野变化时,重新加载该区域的标点
watch(() => mapStore.viewState, async (newView) => {
  const bounds = calculateBoundsFromView(newView);
  await markerService.fetchMarkersByBounds(bounds);
}, { deep: true });

// 保存测量结果
const handleSaveMeasurement = async () => {
  if (!measurementResult.value) return;
  
  try {
    await markerService.saveMeasurement(measurementResult.value);
    ElMessage.success('测量结果已保存');
  } catch (error) {
    ElMessage.error('保存失败: ' + error.message);
  }
};
</script>

在实现这些高级功能时,我遇到的一个典型问题是地图事件与Vue组件生命周期的同步。当地图还在加载,但组件已经尝试调用地图API时,就会出错。我的解决方案是使用一个mapReady的ref状态,只有当天地图SDK完全加载且地图实例初始化完成后,才允许执行相关操作。

另一个实际经验是,自定义图标尽量使用雪碧图(Sprite) 或SVG符号,而不是大量单独的PNG文件。这能显著减少HTTP请求数量,提高加载性能。对于动态颜色的图标,可以使用SVG并通过CSS滤镜或修改SVG源码的方式改变颜色,而不是为每种颜色准备一个文件。

最后,关于测量精度,在最近的一个物流园区规划项目中,客户要求面积测量误差小于0.5%。我们通过强制用户在高缩放级别下操作,并结合手动坐标输入修正,最终达到了0.3%的测量精度,这比单纯使用默认工具提高了近一个数量级。关键是要理解业务对精度的真实需求,而不是盲目追求技术上的极限精度。

vue中使用天地图测距、测面、标点【一】 Vue中如何使用天地图 阅读详情

相关推荐

天地图API进阶:Vue中实现经纬度转换与精准标点

本文详细介绍了在Vue项目中集成天地图API进行高精度地理信息处理的实战方案。重点讲解了经纬度坐标的度分秒与十进制格式转换,并基于此实现了精准标点功能。同时,文章深入探讨了如何利用Haversine公式和球面几何计算,在天地图上实现高精度的测距与测面等空间分析能力,为智慧农业、物流监测等应用提供可靠的技术支持。

lstm7chronicler的博客 349

Vue3+Leaflet+天地图:从零构建动态地图应用的完整指南

本文提供了一份基于Vue3、Leaflet和天地图构建动态地图应用的完整指南。内容涵盖从环境搭建、地图初始化、图层管理与切换,到实现标记、绘制等交互功能的详细步骤,并分享了封装复用Hook及常见问题解决方案,帮助开发者快速上手这一轻量、灵活且功能强大的技术组合。

ll5678的博客 655

vue2+openlayers实现地图测距,测量面积

地图类型切换:支持切换不同的地图底图,如天地图、高德地图和谷歌地图。绘制线条与面积:允许用户在地图上绘制线条和多边形,绘制过程中实时显示测量结果。测量功能:支持测量线条长度和多边形面积,用户可以查看实时的测量数据。编辑和删除功能:用户可以编辑和删除已经绘制的线条和面积,修改后实时更新显示。实现了一个功能丰富的地图应用,支持地图类型切换、绘制线条和多边形、实时测量、编辑和删除等功能。借助 OpenLayers 强大的绘制和交互功能,能够快速构建出一个高效、灵活的地图应用,满足各种测量需求。

weixin_56364552的博客 1512

vue2使用天地图

需求:用vue2使用天地图展示对应点位数据以及开发中出现的问题等,其实天地图的写法和百度地图差不多注意!!!天地图的接口不稳定,时常报错418,官网也是一样的情况,推荐还是使用百度或者高德吧。以下是拷贝的网上的地图坐标系,仅作参考(1)天地图:CGCS2000,2000国家大地坐标系;我们其实很多时候直接用WGS84的坐标来代替CGCS2000坐标。因为CGCS2000的定义与WGS84实质一样。采用的参考椭球非常接近。扁率差异引起椭球面上的纬度和高度变化最大达0.1mm。

请叫我欧皇!的博客 7337

Vue3项目实战:用Leaflet+天地图快速搭建企业级地图应用(附完整代码)

本文详细介绍了如何在Vue3项目中,通过模块化设计整合Leaflet与天地图,快速构建高性能的企业级地图应用。内容涵盖架构设计、图层管理、标记点聚合、绘图工具集成等核心实践,并提供了完整的代码示例和关键的性能优化策略,帮助开发者应对复杂交互与大数据量渲染的挑战。

weixin_29007243的博客 160

Vue3 + Cesium实战:天地图底图与倾斜摄影3DTiles的精准融合与性能调优

本文详细介绍了如何在Vue3项目中结合Cesium实现天地图底图与倾斜摄影3DTiles的精准融合与性能调优。通过坐标系转换、3DTiles位置校准和关键参数调优等技术方案,解决空间位置偏差和性能瓶颈问题,提升Web三维地理信息可视化的效果与效率。

weixin_29295541的博客 406

vue 接入天地图并且在地图上画基站扇形覆盖物

vue 接入天地图并且在地图上画基站扇形覆盖物 vue接入天地图倒是不难,但是要在地图上画扇形倒是有点点麻烦。 为什么选择天地图呢,因为百度地图或者是高德地图在定位的时候都会使用自家的算法在经纬度信息上进行加密,所以说与实际有很大的差距,但是天地图比较专业,当然也有瑕疵了,在天地图开发过程中就会发现,呵呵,个性化的东西就是不如商业气息浓厚的百度地图做的精致。 vue接入天地图 天地图官网 天地图开发者中心 其实天地图和百度地图的用法类似,根据官方提供的文档和案例可是实现很多的功能,然后在vue里面使用的

“跟他人学,和自己比” 4271

基于Vue3与OpenLayers静态导入实现天地图加载的完整开发方案

今天我们走过了一条完整的路线:✅ 用 Vite + Vue3 搭建现代化工程;✅ 放弃 npm 安装 OpenLayers,采用外部资源+容错加载;✅ 成功接入天地图 WMTS 并解决投影偏移;✅ 封装响应式地图组件,支持多实例、动态图层;✅ 设计可扩展架构,预留插件化接口;整套方案已经在多个实际项目中验证过,稳定性杠杠的 💯。下次你再接到“做个地图页面”的需求,就可以淡定地说一句:“小场面,交给我。

weixin_35829279的博客 890

Vue项目实战:天地图测距测面功能完整实现(附源码)

本文详细介绍了在Vue项目中实现天地图测距、测面和标点功能的完整方案。通过实战代码演示了地图初始化、球面距离计算、多边形面积测量等核心功能,并提供了性能优化和组件封装建议,帮助开发者快速构建高精度GIS测量应用。附完整源码解决实际开发中的各种边界问题。

fanta的博客 149

初学者入门机器学习 (ML)的推荐教程

了解基本的机器学习概念并不难。有大量免费的在线博客文章、视频和编码教程可以引导您了解基础知识——从介绍性内容到常见应用程序,再到算法和应用技能。这篇文章总结了一些用于介绍 ML 的最佳免费选项。它按逻辑顺序排列,每个概念都建立在上一个概念的基础上。

u010542847的博客 4637

基于Java+Maven+Testng+RestAssured+Allure+Jenkins搭建一个接口自动化框架

2、有一个提取表达式列,通过编写每个接口的JSON提取表达式,后边在解析Excel时,对接口执行后的响应数据用该表达式提取出来,保存到环境变量,如果某些接口需要前置接口的响应数据,我们就可以从环境变量中获取该数据出来,从而解决了接口关联的问题。1、在之前介绍过全局配置类Contants中添加一个控制台日志开关控制权限,如果选择为false,则控制台不输出日志,将日志输出到allure报表,选择为true,则在控制台输出日志,不输出到allure报表。

专注于技术分享的博主 1196

vue3使用天地图记录,百度地图改使用天地图

老项目地图相关功能改用天地图,处理旧数据的方法,解决踩过的坑。

weixin_44325251的博客 2237

python爬虫豆瓣读书top250+数据清洗+数据库+Java后端开发+Echarts数据可视化(二)

之前的博客已经写了python爬取豆瓣读书top250的相关信息,接下来继续看如何清洗数据。 如果有没看懂的或是不了解上一部分说的是什么内容的,请看https://blog.csdn.net/qq_45804925/article/details/112848887 现在开始具体内容的复习: 1. 豆瓣读书top250信息预处理 #数据清洗 import pandas as pd import re import time # 先读取数据文件 data = pd.read_csv('E:/Class/商.

qq_45804925的博客 4443
上一篇: TensorFlow报错FailedPreconditionError?三步排查法帮你快速定位问题(附环境配置指南)
下一篇: Freeswitch实战:如何用Volte网络实现视频通知(附完整SIP配置)
tequila
博客等级 码龄24年 91粉丝 1499原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值