vue3ts + 高德地图实现自定义位置标定、轨迹

创建高德地图key和安装依赖

参考链接

Vue3使用高德地图(3分钟快速上手)_vue3高德地图demo-CSDN博客

初始化地图 

//@/common/map

import AMapLoader from "@amap/amap-jsapi-loader";
import config from "@/common/config";

export async function initMap(idName:string){
  const AMap = await AMapLoader.load({
    key: config.key,             // 申请好的Web端开发者Key,首次调用 load 时必填
    version:"2.0",      // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
    plugins:['AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Geocoder','AMap.Marker'],       // 需要使用的的插件列表,如比例尺'AMap.Scale'
  })
  const AMapO = AMap
  const map = new AMap.Map(idName,{  //设置地图容器id
    viewMode: "3D",    //是否为3D地图模式
    center: config.centerPoint,  // 初始化地图中心点[x,y]
    zoom: 20,
    resizeEnable: true
  })
  return {AMapO, map}
}
//使用地图的页面

<template>
  <div class="trajectory">
    <div id="trajectoryMap" class="trajectoryMap"></div>
  </div>
</template>


<script setup lang="ts">
import { initMap } from '@/common/map'

    let _AMap: any = nul
    let _map: any = null

    onMounted(() => {
      setMap()
    })

    async function setMap() {
      const { AMapO, map } = await initMap('trajectoryMap')
      _AMap = AMapO
      _map = map
    }
</script>
// 设置标识点
const setIcon=(url:string,size=[31, 50])=>{
  const [width, height] = size
  return new _AMap.Icon({
      image: url,
      size: new _AMap.Size(width, height), // 图标所处区域大小
      imageSize: new _AMap.Size(width, height),
    })
}

位置标定

const devLocation =ref<number[]>([])
let markerList: any = []


// 获取标记的地理位置
const getDevLocationInfo=async()=>{
  // TODO:接口请求获取经纬度
    const {longitude,latitude}=res.data
    let mark=createGps({
         latitude,
         longitude,
    })
    devLocation.value=[mark[0], mark[1]]
    inspectionFact()
}

// 绘制设备位置
const inspectionFact = () => {
  clearRecord()
  
  const marker = new _AMap.Marker({
    position: devLocation.value, //位置
    icon: setIcon(标记Icon引入路径,[41, 40]),
    offset: new _AMap.Pixel(-20, -40),//标记点中心为标记图标最底部
  })
  _map.add(marker)
  markerList.push(marker)
  _map.setZoomAndCenter(18, devLocation.value)
}


// 清除标记
const clearRecord= () => {
  markerList.length&&_map.remove(markerList)
}

轨迹

let _driving:any = null
let markerList: any = []
let pointInfo =reactive({
  startPoint:[]as number[],
  endPoint:[]as number[]
})



//获取轨迹路径
const getTrajectoryPathInfo = async()=>{
      // TODO:接口请求获取轨迹开始/结束点经纬度
      let startPoint= createGps({
        latitude:res.data[0].latitude,
        longitude:res.data[0].longitude
       })

       let endPoint= createGps({
        latitude:res.data[res.data.length - 1].latitude,
        longitude:res.data[res.data.length - 1].longitude
       }) 
      pointInfo.startPoint=[startPoint[0],startPoint[1]]
      pointInfo.endPoint=[endPoint[0],endPoint[1]]
      viewTrack()
}



// 绘制轨迹路径
const viewTrack = async() => {
  clearRecord()
  const startMarker = new _AMap.Marker({
    position: pointInfo.startPoint,
    icon: setIcon(起点icon引入地址),
    offset: new _AMap.Pixel(-15, -50)
  })
  const endMarker = new _AMap.Marker({
    position:  pointInfo.endPoint,
    icon:setIcon(终点icon引入地址),
    offset: new _AMap.Pixel(-15, -50)
  })
  _map.add(startMarker)
  _map.add(endMarker)

  markerList.push(startMarker,endMarker)

  // 绘制路线
  _AMap.plugin('AMap.Driving', function () {
      _driving = new _AMap.Driving({
        map: _map,
        policy: _AMap.DrivingPolicy.LEAST_TIME,
        hideMarkers: true,
        showTraffic: false
      })
      _driving.search(pointInfo.startPoint,pointInfo.endPoint)
  })
}


// 清除标记路线
const clearRecord= () => {
  markerList.length&&_map.remove(markerList)
  _driving&&_driving.clear()
}

GPS转化 

export default class Gps {
  //构造函数
  constructor(obj = {}) {
      let { longitude, latitude } = obj;
      if (longitude === undefined || latitude === undefined) {
          return console.error("经纬度参数不能为空!");
      }
      this.PI = 3.14159265358979324;
      return this.getCoordinate(longitude, latitude);
  };
  //纬度转换
  transformLatitude(x, y) {
      let num = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(M
      num += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2
      num += (20.0 * Math.sin(y * this.PI) + 40.0 * Math.sin(y / 3.0 * this.PI)) * 2.0 / 3
      num += (160.0 * Math.sin(y / 12.0 * this.PI) + 320 * Math.sin(y * this.PI / 30.0)) *
      return num;
  };
  //经度转换
  transformLongitude(x, y) {
      let num = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs
      num += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2
      num += (20.0 * Math.sin(x * this.PI) + 40.0 * Math.sin(x / 3.0 * this.PI)) * 2.0 / 3
      num += (150.0 * Math.sin(x / 12.0 * this.PI) + 300.0 * Math.sin(x / 30.0 * this.PI))
      return num;
  };
  // 坐标转换
  calculation(longitude, latitude) {
      let a = 6378245.0; // 卫星椭球坐标投影到平面地图坐标系的投影因子。
      let ee = 0.00669342162296594323; // 椭球的偏心率。
      let lat = this.transformLatitude(longitude - 105.0, latitude - 35.0);
      let lng = this.transformLongitude(longitude - 105.0, latitude - 35.0);
      let radLat = latitude / 180.0 * this.PI;
      let magic = Math.sin(radLat);
      magic = 1 - ee * magic * magic;
      let sqrtMagic = Math.sqrt(magic);
      lat = (lat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * this.PI);
      lng = (lng * 180.0) / (a / sqrtMagic * Math.cos(radLat) * this.PI);
      return {
          'longitude': lng,
          'latitude': lat,
      };
  };
  // 判断是否为国外坐标
  isOutOfChina(longitude, latitude) {
      if (longitude < 72.004 || longitude > 137.8347) {
          return true;
      };
      if (latitude < 0.8293 || latitude > 55.8271) {
          return true;
      };
      return false;
  };
  // GPS坐标 转 高德坐标
  getCoordinate(longitude, latitude) {
      longitude = Number(longitude);
      latitude = Number(latitude);
      if (this.isOutOfChina(longitude, latitude)) {
          //国外
          return [longitude + obj.longitude,
          latitude + obj.latitude,
          ];
      } else {
          //国内
          let obj = this.calculation(longitude, latitude);
          return [longitude + obj.longitude,
          latitude + obj.latitude,
          ];
      }
  };
}

export function createGps(obj) {
  return new Gps(obj)
}

高德地图自定义标记点marker缩放偏移问题_高德地图开发安卓标记显示不准确-CSDN博客

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用高德地图实现模糊搜索定位,你需要先在项目中引入高德地图的 JavaScript API,并且需要获取高德地图的 API key。接下来,你可以使用 Autocomplete 插件实现模糊搜索,具体实现步骤如下: 1. 在 Vue 3 中安装高德地图的 JavaScript API。 ```bash npm install @amap/amap-jsapi-loader --save ``` 2. 在 main.ts 文件中引入高德地图的 JavaScript API,并在创建 Vue 实例之前加载 JavaScript API。 ```typescript import { createApp } from 'vue' import App from './App.vue' import AMapLoader from '@amap/amap-jsapi-loader' AMapLoader.load({ key: 'your_amap_api_key', version: '2.0', plugins: ['AMap.Autocomplete'] }).then(() => { createApp(App).mount('#app') }) ``` 3. 在组件中使用 Autocomplete 插件实现模糊搜索。 ```vue <template> <div> <input v-model="address" placeholder="请输入地址" /> <ul> <li v-for="suggestion in suggestions" :key="suggestion.id">{{ suggestion.name }}</li> </ul> </div> </template> <script lang="ts"> import { defineComponent, ref } from 'vue' import AMapLoader from '@amap/amap-jsapi-loader' export default defineComponent({ name: 'AutoCompleteDemo', setup() { const address = ref('') const suggestions = ref([]) const search = async () => { const AMap = await AMapLoader.load({ key: 'your_amap_api_key', version: '2.0', plugins: ['AMap.Autocomplete'] }) const autoComplete = new AMap.Autocomplete({ city: '全国' }) autoComplete.search(address.value, (status, result) => { if (status === 'complete' && result.tips) { suggestions.value = result.tips } }) } return { address, suggestions, search } } }) </script> ``` 在这个例子中,我们使用了 ref 函数来创建了两个响应式变量 address 和 suggestions,分别用于存储输入的地址和搜索结果。我们还定义了一个 search 函数,在用户输入时触发,它会通过 AMapLoader.load() 方法加载 Autocomplete 插件,并使用 Autocomplete.search() 方法进行模糊搜索。当搜索完成时,Autocomplete.search() 的回调函数会返回搜索结果,我们将结果存储在 suggestions 变量中,并在页面中渲染出来。 注意,这里我们设置了 city 属性为全国,表示搜索范围为全国。你也可以根据需要修改为特定的城市或区域。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值