vue - vue使用腾讯api进行定位获取,绘制地图、标点、搜索、路线规划

1,前言

首本文主要记录一下在Vue项目里面使用腾讯地图api实现的一些功能。如:引入腾讯地图SDK、定位获取当前经纬度和详细地址、地图marker的使用、关键字搜索功能和路线规划。

我这边实现的效果图如下:
请添加图片描述

2,准备

首先要成为腾讯位置服务开发者或者使用公司提供的key值;才可以使用腾讯地图api,我这里使用的是公司提供的key值;

详细介绍见官网https://lbs.qq.com/webApi/javascriptGL/glGuide/glBasic

3,开始引入api

在vue项目中的根路径下public文件夹的index.html中引入一些api;如下:


<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1, minimum-scale=1">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title>微视频后台管理</title>
  
  	这三个文件是新引入的腾讯地图的api 注意:key值是必须要填的 是一串字符串
    <script type="text/javascript" src="https://mapapi.qq.com/web/mapComponents/geoLocation/v/geolocation.min.js"></script>
    <script type="text/javascript" src="https://map.qq.com/api/gljs?v=1.exp&libraries=service&key=这里是您的key值"></script>
    <script type="text/javascript" src="https://map.qq.com/api/gljs?v=1.exp&key=这里是您的key值"></script>

  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
  </body>
</html>

4,vue组件中使用 - 获取定位

先在mounted生命周期初始化Geolocation定位组件这个类;showPosition是获取成功的回调;里面存放着当前地址的经纬度和详细地址信息;


  mounted() {
    
    
    // 1,初始化腾讯地图
    this.geolocation = new qq.maps.Geolocation('你的key值', 'myapp');
    // 2,并且开始定位
    this.getMyLocation();
  },
  
  methods:{
    
    
     // 获取当前位置
    getMyLocation() {
    
    
      this.geolocation.getLocation(this.showPosition, this.errorPosition); //开启定位
    },
    // 定位成功
    showPosition(position) {
    
    
      console.log('定位成功');
      this.longitude = position.lng;
      this.latitude = position.lat;
      this.queryParams.address = position.city + position.province + position.addr;
      // 定位成功后开始绘制地图
      this.setMap();
    },
    // 定位失败 继续尝试定位
    errorPosition(e) {
    
    
      console.log('定位失败,再次进行定位');
      // 此判断是防止多次绘制地图
      if(!this.map){
    
    
        this.getMyLocation(); 
      }
    },
  }

5,绘制地图和标点

上一步获取定位成功后我这边直接调用setMap方法进行了绘制地图的操作;并以当前为中心点进行标点;如下:
注意:绘制地图需要有一个容器(Dom节点);

/*
     *  setMap 此方法主要是绘制地图和地图标点
     *  绘制地图
     *  绘制地图演示:https://lbs.qq.com/webDemoCenter/glAPI/glMap/createMap
     *  地图标点演示:https://lbs.qq.com/webDemoCenter/glAPI/glMarker/glImagetext
     *  路线规划演示:https://lbs.qq.com/webDemoCenter/glAPI/glPolyline/polylineRoutePlan
     */
    setMap() {
    
    
	  // 防止重复绘制地图
      if(this.map) {
    
    
      	return;
      };

      // 获取存放地图的容器
      this.mapEl = document.getElementById('mapItem');
      //设置地图中心点
      this.startPosition = new TMap.LatLng(this.latitude, this.longitude);
      //定义工厂模式函数
      var myOptions = {
    
    
        rotation: 20, //设置地图旋转角度
        pitch: 30, //设置俯仰角度(0~45)
        zoom: 12, //设置地图缩放级别
        center: this.startPosition, //设置地图中心点坐标
        // mapTypeId:  window.TMap.MapTypeId.ROADMAP, //设置地图样式详情参见MapType
      };
      try {
    
    
        // 开始生成地图
        this.map = new TMap.Map(this.mapEl, myOptions);
      } catch (error) {
    
    
        console.error('error:', error);
      }
      // 地图标点官方演示请见:https://lbs.qq.com/webDemoCenter/glAPI/glMarker/glImagetext
      new TMap.MultiMarker({
    
    
        map: this.map, //指定地图容器
        styles: {
    
    
          // 点标记样式
          marker1: new TMap.MarkerStyle({
    
    
            width: 20, // 样式宽
            height: 30, // 样式高
            anchor: {
    
     x: 10, y: 30 }, // 描点位置
          }),
        },
        // 点标记数据数组
        geometries: [
          {
    
    
            id: 'demo',
            styleId: 'marker1', // 和上面styles里面的marker1 向对应
            position: new TMap.LatLng(this.latitude, this.longitude), // 标点的位置
            properties: {
    
    
              title: 'marker',
            },
          },
        ],
      });
    },

6,关键字搜索功能

输入地址然后点击搜索按钮进行搜索;如下图:
注意:搜索到的地址列表(searchList )然后使用抽屉组件并通过列表显示出来;点击每一项可以获取它的详细地址和经纬度信息;

   /* 点击搜索 搜索地址列表
     * 官方演示地址为:https://lbs.qq.com/webDemoCenter/glAPI/glServiceLib/suggestion
     */
    onSearch() {
    
    
      this.searchItem = new TMap.service.Search({
    
     pageSize: 10 });
      // 搜索类
      this.suggest = new TMap.service.Suggestion({
    
    
        pageSize: 10, // 返回结果每页条目数
        region: this.city, // 限制城市范围
        regionFix: true, // 搜索无结果时是否固定在当前城市
      });
      if (this.onSearchValue) {
    
    
        // 请求腾讯地图接口
        this.suggest.getSuggestions({
    
     keyword: this.onSearchValue, location: this.map.getCenter() }).then((result) => {
    
    
          this.searchList = result.data;
          if (typeof this.searchList == 'object') {
    
    
            this.souShow = true;
          }
        });
      } else {
    
    
        Toast('请输入地点再进行搜索!');
      }
    },

在这里插入图片描述

扫描二维码关注公众号,回复: 14737128 查看本文章

7,驾车线路规划

线路规划需要有起点和终点的经纬度;起点就是当前定位的经纬度,终点就是用户选择的地址的经纬度;方法如下:

    /* 路线规划方法  
    * 参数:前两个参数是起点的经纬度  后两个参数是终点的经纬度
    */
    goToThere(startLat,startLng,endLat,endLng) {
    
    
      let startPosition = new TMap.LatLng(startLat, startLng); // 路线规划起点
      let endPosition = new TMap.LatLng(endLat, endLng); // 路线规划起点
      // 然后开始规划路线
      this.destination.marker = new TMap.MultiMarker({
    
    
        // 创造MultiMarker创建起点和终点的标点样式
        id: 'marker-layer',
        map: this.map,// 使用之前已经绘制好的地图 进行起点和终点的标点
        styles: {
    
    
          start: new TMap.MarkerStyle({
    
    
            width: 25,
            height: 35,
            anchor: {
    
     x: 16, y: 32 },
            src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/start.png',
          }),
          end: new TMap.MarkerStyle({
    
    
            width: 25,
            height: 35,
            anchor: {
    
     x: 16, y: 32 },
            src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/end.png',
          }),
        },
         //点标记数据数组
        geometries: [
          {
    
    
            id: 'start',
            styleId: 'start',
            position:startPosition,
          },
          {
    
    
            id: 'end',
            styleId: 'end',
            position: endPosition,
          },
        ],
      });

      /* 
      驾车路线规划链接:https://lbs.qq.com/webDemoCenter/glAPI/glServiceLib/driving
      路线规划演示:https://lbs.qq.com/webDemoCenter/glAPI/glPolyline/polylineRoutePlan
      */
      //新建一个驾车路线规划类
      this.destination.driving = new TMap.service.Driving({
    
    
        mp: false, // 是否返回多方案
        policy: 'PICKUP,NAV_POINT_FIRST', // 规划策略
      });

      this.destination.driving.search({
    
     from: startPosition, to: endPosition }).then((result) => {
    
    
        // 搜索路径 案例这边展示的是第一个中情况
        // result.result.routes[0].steps.forEach((step, index) => {
    
    
        //   document.getElementById('instruction').innerHTML += `<p>${index + 1}. ${step.instruction}</p>`;
        // });

        // 展示路线引导  有可能是多条路线的展示
        this.queryParams.routesList = JSON.stringify(result.result.routes);
        result.result.routes.map((item, index) => {
    
    
          this.displayPolyline(item.polyline, index);
        });
        // 关闭抽屉
        this.souShow = false;
      });
    },

    // 绘制路径折线样式
    displayPolyline(pl, num) {
    
    
      // 第一次进来这个判断是不成立的
      if (this.polylineLayer) {
    
    
        // updateGeometries 这个方法是更新图层
        this.polylineLayer.updateGeometries([
          {
    
    
            id: `p_${
      
      num}`,
            styleId: `style_${
      
      num}`, //和下面的styleID一一对应
            paths: pl,
          },
        ]);
      } else {
    
    
        // TMap.MultiPolyline  此方法用来构建折线 (地图线路规划)
        this.polylineLayer = new TMap.MultiPolyline({
    
    
          id: 'polyline-layer',
          map: this.map,
          styles: {
    
    
            style_0: new TMap.PolylineStyle({
    
    
              color: '#11CA53', //线填充色
              width: 6, //折线宽度
              borderWidth: 0, //边线宽度
              borderColor: '#11CA53', //边线颜色
              lineCap: 'round', //线端头方式
            }),
            style_1: new TMap.PolylineStyle({
    
    
              color: '#3777FF',
              width: 6,
              borderWidth: 0,
              borderColor: '#3777FF',
              lineCap: 'round',
            }),
            style_2: new TMap.PolylineStyle({
    
    
              color: '#CC0000', //线填充色
              width: 6, //折线宽度
              borderWidth: 0, //边线宽度
              borderColor: '#CC0000', //边线颜色
              lineCap: 'round', //线端头方式
            }),
          },
          geometries: [
            {
    
    
              id: `p_0`,
              styleId: `style_0`,
              paths: pl,
            },
          ],
        });
      }
    },

注意:

下面是此案例的全部代码,包括template和data里面的数据,此案例只是介绍腾讯地图api的一些简单使用,想要了解更多请参考官方文档;参考文档我放到最后面了;

8,演示组件中的全部代码

<template>
  <div class="app">
    <div class="content">
      <!-- 导航栏 -->
      <van-nav-bar title="测试腾讯地图" left-text="返回" left-arrow>
        <template #right>
          <van-icon name="search" size="18" />
        </template>
      </van-nav-bar>

      <!-- 获取当前所在位置 -->
      <van-field v-model="queryParams.address" rows="1" autosize clearable readonly right-icon="location-o" type="textarea" label="当前所在位置" placeholder="" input-align="right" />
      <!-- 搜索地址 -->
      <van-search v-model="onSearchValue" show-action label="地址" placeholder="请输入搜索关键词">
        <template #action>
          <div @click="onSearch">搜索</div>
        </template>
      </van-search>
      <!-- 展示地图用的 -->
      <div id="mapItem"></div>
    </div>
    <!-- 下方展示地图列表的抽屉 -->
    <van-popup v-model="souShow" position="bottom" :style="{ height: '40%' }">
      <div class="list-main">
        <div class="list-one" v-for="(item,index) in searchList" :key="index" @click="currentItem(item)">
          <div class="one-left">
            <div class="title">{
    
    {
    
     item.title }}</div>
            <div class="text">{
    
    {
    
     item.address }}</div>
          </div>
          <div class="one-right">
            <van-icon name="guide-o" />
          </div>
        </div>
      </div>
    </van-popup>
    <canvas id="canvasCamera" :height="Height"></canvas>
  </div>
</template>
<script>
import {
    
     Toast } from 'vant';
export default {
    
    
  directives: {
    
    },
  components: {
    
    },
  data() {
    
    
    return {
    
    
      queryParams: {
    
    
        address: '', //当前所在位置
      },
      geolocation: null, // 地图对象
      onSearchValue: '徐家汇', // 你到达的位置 也就是搜索框输入的地点
      //这两个是经纬度坐标 
      longitude: null, // 121.548752
      latitude: null, // 31.227493
      //地图绘制对象
      map: null,
      // 当前城市
      city: '上海',
      // 地图的中心点
      startPosition: null,
      // 存放地图的容器对象
      mapEl: null,
      // 搜素地图的列表
      searchList: null,
      // 控制抽屉的显示于隐藏
      souShow: false,
      // 地图折线
      polylineLayer: null,
      suggest: null,
      // 路线规划相关信息
      destination: {
    
    
        marker: null, //地图规划
        driving: null, //驾车规划
      },
      Height:400,
    };
  },
  mounted() {
    
    
    // 1,初始化腾讯地图
    this.geolocation = new qq.maps.Geolocation('V6VBZ-KD2OW-ATORL-RRKFW-QICF2-C3B7H', 'myapp');
    // 2,并且开始定位
    this.getMyLocation();
  },
  methods: {
    
    
    // 获取当前位置
    getMyLocation() {
    
    
      this.geolocation.getLocation(this.showPosition, this.errorPosition); //开启定位
    },
    // 定位成功
    showPosition(position) {
    
    
      console.log('定位成功');
      this.longitude = position.lng;
      this.latitude = position.lat;
      this.queryParams.address = position.city + position.province + position.addr;
      // 定位成功后开始绘制地图
      this.setMap();
    },
    // 定位失败 继续尝试定位
    errorPosition(e) {
    
    
      console.log('定位失败,再次进行定位');
      // 此判断是防止多次绘制地图
      if(!this.map){
    
    
        this.getMyLocation(); 
      }
    },

    /* 点击搜索中的其中一项 item的location对象里面有 此项的经纬度 */
    currentItem(item) {
    
    
      // 前两个参数是起点的经纬度  后两个参数是终点的经纬度
      this.goToThere(this.latitude,this.longitude,item.location.lat,item.location.lng)
    },

    /* 点击搜索 搜索地址列表
     * 官方演示地址为:https://lbs.qq.com/webDemoCenter/glAPI/glServiceLib/suggestion
     */
    onSearch() {
    
    
      this.searchItem = new TMap.service.Search({
    
     pageSize: 10 });
      // 搜索类
      this.suggest = new TMap.service.Suggestion({
    
    
        pageSize: 10, // 返回结果每页条目数
        region: this.city, // 限制城市范围
        regionFix: true, // 搜索无结果时是否固定在当前城市
      });
      if (this.onSearchValue) {
    
    
        // 请求腾讯地图接口
        this.suggest.getSuggestions({
    
     keyword: this.onSearchValue, location: this.map.getCenter() }).then((result) => {
    
    
          this.searchList = result.data;
          if (typeof this.searchList == 'object') {
    
    
            this.souShow = true;
          }
        });
      } else {
    
    
        Toast('请输入地点再进行搜索!');
      }
    },

    // 这两个是展示模式
    change2D() {
    
    
      this.map.setViewMode('2D');
    },
    change3D() {
    
    
      this.map.setViewMode('3D');
      this.map.setPitch(70);
    },

    /*
     *  setMap 此方法主要是绘制地图和地图标点
     *  绘制地图
     *  绘制地图演示:https://lbs.qq.com/webDemoCenter/glAPI/glMap/createMap
     *  地图标点演示:https://lbs.qq.com/webDemoCenter/glAPI/glMarker/glImagetext
     *  路线规划演示:https://lbs.qq.com/webDemoCenter/glAPI/glPolyline/polylineRoutePlan
     */
    setMap() {
    
    

      if(this.map) return; // 防止重复绘制地图

      // 获取存放地图的容器
      this.mapEl = document.getElementById('mapItem');
      //设置地图中心点
      this.startPosition = new TMap.LatLng(this.latitude, this.longitude);
      //定义工厂模式函数
      var myOptions = {
    
    
        rotation: 20, //设置地图旋转角度
        pitch: 30, //设置俯仰角度(0~45)
        zoom: 12, //设置地图缩放级别
        center: this.startPosition, //设置地图中心点坐标
        // mapTypeId:  window.TMap.MapTypeId.ROADMAP, //设置地图样式详情参见MapType
      };

      try {
    
    
        // 开始生成地图
        this.map = new TMap.Map(this.mapEl, myOptions);
      } catch (error) {
    
    
        console.error('error:', error);
      }

      // 地图标点官方演示请见:https://lbs.qq.com/webDemoCenter/glAPI/glMarker/glImagetext
      new TMap.MultiMarker({
    
    
        map: this.map, //指定地图容器
        styles: {
    
    
          // 点标记样式
          marker1: new TMap.MarkerStyle({
    
    
            width: 20, // 样式宽
            height: 30, // 样式高
            anchor: {
    
     x: 10, y: 30 }, // 描点位置
          }),
        },
        // 点标记数据数组
        geometries: [
          {
    
    
            id: 'demo',
            styleId: 'marker1', // 和上面styles里面的marker1 向对应
            position: new TMap.LatLng(this.latitude, this.longitude), // 标点的位置
            properties: {
    
    
              title: 'marker',
            },
          },
        ],
      });
    },

    /* 路线规划方法  
    * 参数:前两个参数是起点的经纬度  后两个参数是终点的经纬度
    */
    goToThere(startLat,startLng,endLat,endLng) {
    
    
      let startPosition = new TMap.LatLng(startLat, startLng); // 路线规划起点
      let endPosition = new TMap.LatLng(endLat, endLng); // 路线规划起点
      // 然后开始规划路线
      this.destination.marker = new TMap.MultiMarker({
    
    
        // 创造MultiMarker创建起点和终点的标点样式
        id: 'marker-layer',
        map: this.map,// 使用之前已经绘制好的地图 进行起点和终点的标点
        styles: {
    
    
          start: new TMap.MarkerStyle({
    
    
            width: 25,
            height: 35,
            anchor: {
    
     x: 16, y: 32 },
            src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/start.png',
          }),
          end: new TMap.MarkerStyle({
    
    
            width: 25,
            height: 35,
            anchor: {
    
     x: 16, y: 32 },
            src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/end.png',
          }),
        },
         //点标记数据数组
        geometries: [
          {
    
    
            id: 'start',
            styleId: 'start',
            position:startPosition,
          },
          {
    
    
            id: 'end',
            styleId: 'end',
            position: endPosition,
          },
        ],
      });

      /* 
      驾车路线规划链接:https://lbs.qq.com/webDemoCenter/glAPI/glServiceLib/driving
      路线规划演示:https://lbs.qq.com/webDemoCenter/glAPI/glPolyline/polylineRoutePlan
      */
      //新建一个驾车路线规划类
      this.destination.driving = new TMap.service.Driving({
    
    
        mp: false, // 是否返回多方案
        policy: 'PICKUP,NAV_POINT_FIRST', // 规划策略
      });

      this.destination.driving.search({
    
     from: startPosition, to: endPosition }).then((result) => {
    
    
        // 搜索路径 案例这边展示的是第一个中情况
        // result.result.routes[0].steps.forEach((step, index) => {
    
    
        //   document.getElementById('instruction').innerHTML += `<p>${index + 1}. ${step.instruction}</p>`;
        // });

        // 展示路线引导  有可能是多条路线的展示
        this.queryParams.routesList = JSON.stringify(result.result.routes);
        result.result.routes.map((item, index) => {
    
    
          this.displayPolyline(item.polyline, index);
        });
        // 关闭抽屉
        this.souShow = false;
      });
    },

    // 绘制路径折线
    displayPolyline(pl, num) {
    
    
      // 第一次进来这个判断是不成立的
      if (this.polylineLayer) {
    
    
        // updateGeometries 这个方法是更新图层
        this.polylineLayer.updateGeometries([
          {
    
    
            id: `p_${
      
      num}`,
            styleId: `style_${
      
      num}`, //和下面的styleID一一对应
            paths: pl,
          },
        ]);
      } else {
    
    
        // TMap.MultiPolyline  此方法用来构建折线 (地图线路规划)
        this.polylineLayer = new TMap.MultiPolyline({
    
    
          id: 'polyline-layer',
          map: this.map,
          styles: {
    
    
            style_0: new TMap.PolylineStyle({
    
    
              color: '#11CA53', //线填充色
              width: 6, //折线宽度
              borderWidth: 0, //边线宽度
              borderColor: '#11CA53', //边线颜色
              lineCap: 'round', //线端头方式
            }),
            style_1: new TMap.PolylineStyle({
    
    
              color: '#3777FF',
              width: 6,
              borderWidth: 0,
              borderColor: '#3777FF',
              lineCap: 'round',
            }),
            style_2: new TMap.PolylineStyle({
    
    
              color: '#CC0000', //线填充色
              width: 6, //折线宽度
              borderWidth: 0, //边线宽度
              borderColor: '#CC0000', //边线颜色
              lineCap: 'round', //线端头方式
            }),
          },
          geometries: [
            {
    
    
              id: `p_0`,
              styleId: `style_0`,
              paths: pl,
            },
          ],
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
#mapItem {
    
    
  /*地图(容器)显示大小*/
  width: 100%;
  height: 400px;
}

// 搜索列表的样式
.list-main {
    
    
  box-sizing: border-box;
  padding: 10px 20px;
  width: 100%;
  height: 100%;
  overflow-y: auto;
  .list-one {
    
    
    width: 100%;
    padding: 10px 0;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
    border-bottom: 1px solid #eee;
    .one-left {
    
    
      max-width: 70%;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      .title {
    
    
        color: #000;
      }
      .text {
    
    
        color: #666;
        margin-top: 5px;
      }
    }
    .one-right {
    
    
      width: 50px;
    }
  }
}

</style>

9,参考链接

[1]绘制地图演示: https://lbs.qq.com/webDemoCenter/glAPI/glMap/createMap

[2]地图标点演示: https://lbs.qq.com/webDemoCenter/glAPI/glMarker/glImagetext

[3]路线规划演示: https://lbs.qq.com/webDemoCenter/glAPI/glPolyline/polylineRoutePlan

[4]驾车路线规划链接: https://lbs.qq.com/webDemoCenter/glAPI/glServiceLib/driving

猜你喜欢

转载自blog.csdn.net/qq_43886365/article/details/129427623
vue