The vue project introduces Baidu map BMapGL and BMap instances, as well as the introduction of auxiliary tools BMapGLLib and BMapGL mouse drawing function

Record the api used by the vue project to use Baidu Maps and the pits that have been stepped on, so as to reduce future references and avoid detours. It's for the record, it's the first time to post, please give me your advice. Without further ado, let's go!

1. Citing Baidu Maps

There is not much to say about the account key here, just go to the link and register by yourself.

First, add the following code to your project's index.html:
This is BMap

<script type="text/javascript" src="//api.map.baidu.com/api?v=3.0&ak=您的密钥"></script>

This is BMapGL

<script src="//api.map.baidu.com/api?type=webgl&v=1.0&ak=您的密钥"></script>

If you need to use the auxiliary tool BMapGLLib, you have to put the following two

<link href="//mapopen.cdn.bcebos.com/github/BMapGLLib/DrawingManager/src/DrawingManager.min.css" rel="stylesheet">
<script type="text/javascript" src="//mapopen.cdn.bcebos.com/github/BMapGLLib/DrawingManager/src/DrawingManager.min.js"></script>

2. Use Baidu map in the project

2-1. Page structure

(1) Create a map container element

<div class="map-body" :id="mapId"></div>

(2) Set the size of the container style

.map-body {
    
    
  position: relative;
  height: 500px;
  border: 1px solid #dcdfe6;
}

2-2, js logic part

(1) Create a map instance

createMap(lgt, lat) {
    
    
      // this.maploading=true;
      this.map = new BMapGL.Map(this.mapId, {
    
     enableMapClick: false }) // 创建Map实例,GL版命名空间为BMapGL(鼠标右键控制倾斜角度)
      this.map.centerAndZoom(new BMapGL.Point(lgt, lat), 11)      // 初始化地图,设置中心点坐标和地图级别
      this.map.enableScrollWheelZoom(true)// 开启鼠标滚轮缩放
    },

(2) Assign the map to a global variable for subsequent use

  data() {
    
    
    return {
    
    
    map: "",
    mapId: "", //我这里采用了动态id这个不是必须的,看自己需求来
    }
    created() {
    
    
    this.mapId = 'map' + new Date().getTime();

(3) Set the coordinates of the center point
Here we use the Point class under the BMapGL namespace to create a coordinate point. The Point class describes a geographic coordinate point, where 116.404 represents longitude and 39.915 represents latitude. (Coordinates of Tiananmen Square)

    const point = new BMapGL.Point(116.404, 39.915);

Note:
When using the Baidu Maps JavaScript API service, you need to use Baidu BD09 coordinates. If you use other coordinates (WGS84, GCJ02) for display, you need to convert other coordinates to BD09 first. For details, please refer to the coordinate conversion instructions. Do not use non- The official conversion method.

(4) Map initialization

    created() {
    
    
    this.mapId = 'map' + new Date().getTime();
    const point = new BMapGL.Point(116.404, 39.915);
    //创建地图
    this.$nextTick(() => {
    
    
      this.createMap(point.lng, point.lat);
    })
  },

Up to now, Baidu map has been successfully created on your page.
Attached picture:
Vue introduces Baidu map BMap

3. Use Baidu map auxiliary tool BMapGLLib in the project

The current requirement is to mark points on the page, draw rectangles, and some circular marking lines. The auxiliary tools of Baidu Maps just come with these two functions.

3-1. Page structure part

(1) The html structure and css style of the auxiliary toolbar

   <ul class="drawing-panel">
     <li class="bmap-btn bmap-marker" @click="draw('marker')"
       :style="{ 'background-position-y': actNav === 'marker' ? '-52px' : '0px' }"></li>
     <li class="bmap-btn bmap-polyline" @click="draw('polyline')"
       :style="{ 'background-position-y': actNav === 'polyline' ? '-52px' : '0px' }"></li>
     <li class="bmap-btn bmap-rectangle" @click="draw('rectangle')"
       :style="{ 'background-position-y': actNav === 'rectangle' ? '-52px' : '0px' }"></li>
     <li class="bmap-btn bmap-polygon" @click="draw('polygon')"
       :style="{ 'background-position-y': actNav === 'polygon' ? '-52px' : '0px' }"></li>
     <li class="bmap-btn bmap-circle" @click="draw('circle')"
       :style="{ 'background-position-y': actNav === 'circle' ? '-52px' : '0px' }"></li>
   </ul>
.drawing-panel {
    
    
  z-index: 999;
  position: absolute;
  top: 14rem;
  margin-left: 2.5rem;
  padding-left: 0;
  border-radius: .25rem;
  height: 47px;
  box-shadow: 0 2px 6px 0 rgba(27, 142, 236, 0.5);
}

.bmap-btn {
    
    
  border-right: 1px solid #d2d2d2;
  float: left;
  width: 64px;
  height: 100%;
  background-image: url(//api.map.baidu.com/library/DrawingManager/1.4/src/bg_drawing_tool.png);
  cursor: pointer;
}

.drawing-panel .bmap-marker {
    
    
  background-position: -65px 0;
}

.drawing-panel .bmap-polyline {
    
    
  background-position: -195px 0;
}

.drawing-panel .bmap-rectangle {
    
    
  background-position: -325px 0;
}

.drawing-panel .bmap-polygon {
    
    
  background-position: -260px 0;
}

.drawing-panel .bmap-circle {
    
    
  background-position: -130px 0;
}

The effect of the structure is as follows:
Auxiliary toolBMapGLLib

3-2, js logic part

After the above map is initialized, you can use the mouse drawing tool to draw the required drawing
(1) Instantiate the mouse drawing tool

    draw(drawingType) {
    
    
      console.log(drawingType, '666')
      this.actNav = drawingType
      /**这里看需求可以把它设置为全局变量。
      *我这里需求需要,故设置了全局变量,以下代码就注释掉了*/
      // const styleOptions = {
    
    
      //   strokeColor: '#5E87DB',   // 边线颜色
      //   fillColor: '#5E87DB',     // 填充颜色。当参数为空时,圆形没有填充颜色
      //   strokeWeight: 2,          // 边线宽度,以像素为单位
      //   strokeOpacity: 1,         // 边线透明度,取值范围0-1
      //   fillOpacity: 0.2          // 填充透明度,取值范围0-1
      // };
      // const labelOptions = {
    
    
      //   borderRadius: '2px',
      //   background: '#FFFBCC',
      //   border: '1px solid #E1E1E1',
      //   color: '#703A04',
      //   fontSize: '12px',
      //   letterSpacing: '0',
      //   padding: '5px'
      // };

      // 实例化鼠标绘制工具
      const drawingManager = new BMapGLLib.DrawingManager(this.map, {
    
    
        //isOpen: true,        // 是否开启绘制模式
        enableCalculate: false, // 绘制是否进行测距测面
        enableSorption: true, // 是否开启边界吸附功能
        sorptiondistance: 20, // 边界吸附距离
        circleOptions: this.styleOptions, // 圆的样式
        polylineOptions: this.styleOptions, // 线的样式
        polygonOptions: this.styleOptions, // 多边形的样式
        rectangleOptions: this.styleOptions, // 矩形的样式
        labelOptions: this.labelOptions,  // label样式
      })
      // 进行绘制
      if (drawingManager._isOpen && drawingManager.getDrawingMode() === drawingType) {
    
    
        drawingManager.close();
      } else {
    
    
        drawingManager.setDrawingMode(drawingType);
        drawingManager.open();
      }
      /** 我这里需求是圆形和矩形还有点的标注,
      *还有两种就没有写它的监听事件,也是差不多的,
      *可以对照一下官方api和我写的就基本上差不多了,
      *如果有谁需要,我有时间也可以继续把剩下两种监听事件补上 */
      // 监听事件
      if (drawingType == 'rectangle') {
    
    
        // 监听矩形绘制完成事件
        drawingManager.addEventListener("overlaycomplete", (e) => {
    
    
          // 获取矩形对象
          const rectangle = e.overlay;
          // 获取矩形的四个顶点
          const points = rectangle.getPath();
          console.log(points, "顶点");
          this.scope_point = points;
        });
      } else if (drawingType == 'circle') {
    
    
        // 监听圆形绘制完成事件
        drawingManager.addEventListener("overlaycomplete", (e) => {
    
    
          // 获取圆形对象
          const circle = e.overlay;
          // 获取圆形的圆心
          const center = circle.getCenter();
          console.log(center, "圆心");
          // 获取圆形的半径
          const radius = circle.getRadius();
          console.log(radius, "半径");
          this.scope_point = center;
          this.scope_radius = radius;
        });
      } else if (drawingType == 'marker') {
    
    
        drawingManager.addEventListener("overlaycomplete", (e) => {
    
    
          // 获取标注对象
          const marker = e.overlay;
          // 获取标注的经纬度坐标
          this.point = marker.getPosition();
          // 创建地理编码服务实例
          const geocoder = new BMapGL.Geocoder();
          // 将经纬度坐标解析为地址信息
          geocoder.getLocation(this.point, (result) => {
    
    
            this.newForm.address = result.address;
            console.log(this.point, result.address, "地址");
          });
        });
      }
    },

The effect is as shown in the figure (I only need these three types, and the others are commented out):
BMapGL mouse drawing function

4. Use BMap instance in the project

Note:
The big pit is coming! ! ! The map instance created by the BMapGL class does not support the addOverlay method, and it does not support directly using the mouse drawing tool (BMapLib.DrawingManager class) to draw a rectangular frame on the map, so it can only be replaced by BMap). Going on, because I need to show the callouts I just drew. . .
(1) Reinitialize a map instance (BMap)

 this.map = new BMap.Map(this.mapId, {
    
     enableMapClick: false });
 this.map.centerAndZoom(new BMap.Point(point_location[1], point_location[0]), 11)      // 初始化地图,设置中心点坐标和地图级别我这里的point_location是后台返回的坐标,跟上面的类似
 this.map.enableScrollWheelZoom(true)// 开启鼠标滚轮缩放

(2) Create marker points

// 创建标记点的坐标
const point = new BMap.Point(point_location[1], point_location[0]);//point_location后台返回字段
console.log(point, "坐标")
// 创建标记点对象
const marker = new BMap.Marker(point);
// 将标记点添加到地图上
this.map.addOverlay(marker);

(3) Create a rectangular frame object

// 创建矩形框对象
 const rectangle = new BMap.Polygon([
   new BMap.Point(this.rectangle[3], this.rectangle[2]), //rectangle后台返回的坐标
   new BMap.Point(this.rectangle[5], this.rectangle[4]),
   new BMap.Point(this.rectangle[7], this.rectangle[6]),
   new BMap.Point(this.rectangle[9], this.rectangle[8]),
 ], this.styleOptions); //styleOptions之前的全局变量

 // 将矩形框添加到地图上
 this.map.addOverlay(rectangle);
 // 设置地图视野,使得矩形框完全显示在地图视野内
 this.map.setViewport(rectangle.getPath());

(4) Create a circular object

 // 创建圆心坐标
 const center = new BMap.Point(this.rectangle[1], this.rectangle[0]);//rectangle后台返回的圆形坐标

 // 创建圆形标注对象
 const circle = new BMap.Circle(center, this.scope_radius, this.styleOptions);

 // 将圆形标注添加到地图上
 this.map.addOverlay(circle);

5. Call it a day, get off work! ! !get off work!

Guess you like

Origin blog.csdn.net/lFFFFFFl/article/details/128483421