vue高德定位及地图使用 canvas生成分享图和二维码

464 阅读3分钟

# PC端IP定位和H5端GPS网络精确定位使用

各种使用key请在官网申请 lbs.amap.com/

按 NPM 方式使用 Loader

安装:

npm i @amap/amap-jsapi-loader --save
import AMapLoader from '@amap/amap-jsapi-loader';
AMapLoader.load({
        key: '', // 申请好的Web端开发者Key,首次调用 load 时必填
        version: '2.0', // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
        plugins: [ // 用到的功能自行开启
          // 'AMap.CircleEditor', // 圆形编辑器插件
          'AMap.Geolocation', // 定位控件,用来获取和展示用户主机所在的经纬度位置
          // 'AMap.Geocoder', // 地理编码与逆地理编码服务,用于地址描述与坐标间的相互转换
          // 'AMap.Autocomplete',
          // 'AMap.PlaceSearch',
          'AMap.CitySearch'
        ] // 需要使用的的插件列表,如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          if (baseType !== 'mobile') { // **此处是用全局参数判断pc和mobile(h5)自行定义**
            // PC端IP定位
            AMap.plugin('AMap.CitySearch', function () {
              var citySearch = new AMap.CitySearch()
              citySearch.getLocalCity(function (status, result) {
                if (status === 'complete' && result.info === 'OK') {
                  // 查询成功,result即为当前所在城市信息
                }
              })
            })
          } else {
            // H5端精确定位
            AMap.plugin('AMap.Geolocation', function () {
              var geolocation = new AMap.Geolocation({
                // 是否使用高精度定位,默认:true
                enableHighAccuracy: true,
                // 设置定位超时时间,默认:无穷大
                timeout: 10000
              })
              geolocation.getCurrentPosition()
              AMap.event.addListener(geolocation, 'complete', onComplete)
              AMap.event.addListener(geolocation, 'error', onError)
              function onComplete(data) {
                // console.log('精确定位:', data)
              }
              // 解析定位错误信息
              function onError(data) {
                console.log(data)
              }
            })
          }
        })
        .catch((e) => {
          console.log(e)
        })

注意 Google浏览器不支持H5精确定位

# 地图使用

 AMapLoader.load({
  key: '', // 申请好的Web端开发者Key,首次调用 load 时必填
  version: '2.0', // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
  plugins: [] // 需要使用的的插件列表,如比例尺'AMap.Scale'等
})
  .then((AMap) => {
    console.log(AMap)
    this.mapInit(AMap)
  })
  .catch((e) => {
    console.log(e)
  })

地图绘制 可传入AMap 或者 不传入使用window.AMap

    mapInit(AMap) {
      // 移除已创建的 marker
      // this.map.remove(marker)
      // console.log(AMap)
      var icon, marker, text
      // 创建 AMap.Icon 实例:
      icon = new AMap.Icon({
        size: new AMap.Size(40, 46), // 图标尺寸
        image: require('./assets/img/map/icon.png'), // Icon的图像
        // imageOffset: new AMap.Pixel(0, -60), // 图像相对展示区域的偏移量,适于雪碧图等
        imageSize: new AMap.Size(40, 46) // 根据所设置的大小拉伸或压缩图片
      })
      // 将 Icon 实例添加到 marker 上:  可单个或多个
      for (var i = 0; i < this.locationdata.length; i++) {
          marker = new AMap.Marker({
            position: new AMap.LngLat(...this.locationdata[i]), // 经纬度对象,也可以是经纬度构成的一维数组[116.39, 39.9]
            // position: new AMap.LngLat(116.39, 39.9),
            offset: new AMap.Pixel(-10, -10),
            // content: content, // 自定义点标记覆盖物内容
            icon: icon, // 添加 Icon 实例
            title: '北京',
            zoom: 13
          })
          // 创建纯文本标记 还有其他文本方式 可自行查看官网文档
          text = new AMap.Text({
            text:
              '<div><p style="background: #ddd;padding: 12px;font-weight: 700;word-wrap: break-word;display: -webkit-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;overflow: hidden;">' +
              this.citylist[i].dealerFullName +
              '</p><p style="padding: 12px 12px 0;white-space: normal;word-wrap: break-word;display: -webkit-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;overflow: hidden;">' +
              this.citylist[i].address +
              '</p><p style="padding: 12px;">' +
              this.citylist[i].tel +
              '</p></div>',
            anchor: 'center', // 设置文本标记锚点
            draggable: true,
            cursor: 'pointer',
            angle: 0,
            style: {
              padding: '0',
              'margin-top': '-3.5rem',
              'border-radius': '.25rem',
              'background-color': 'white',
              width: '15rem',
              'border-width': 0,
              'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
              // 'text-align': 'center',
              'font-size': '12px',
              color: '#000'
            },
            position: [...this.locationdata[i]]
          })
          // 点击触发某个添加的地图inco
          marker.on('click', function (e) {
            console.log(e)
          })
          this.map.add(text) // 渲染地图内标注文案
          this.map.add(marker) // 渲染地图内标注Icon的图像
      }
    }
  }

# canvas生成分享图和二维码

import html2canvas from 'html2canvas'
import QRCode from 'qrcodejs2'
import { saveAs } from 'file-saver'

请先npm下载 html2canvas QRCode file-saver

QRCodeFun() {
  this.$refs.qrcode.innerHTML = '' //清除二维码方法一
  let text
  if (window.location.href.indexOf('#') !== -1) {
    text = 'https://' + window.location.host + '/#/details-car?id=' + this.dataDa.stockNo
  } else {
    text = 'https://' + window.location.host + '/details-car?id=' + this.dataDa.stockNo
  }
  var qrcode = new QRCode(this.$refs.qrcode, {
    text: text, //页面地址 ,如果页面需要参数传递请注意哈希模式#
    width: 60,
    height: 60,
    colorDark: '#000000',
    colorLight: '#ffffff',
    correctLevel: QRCode.CorrectLevel.H
  })
  console.log(qrcode)
  // qrcode.clear(); // 清除二维码方法二
},

页面使用

<div ref="qrcode" />

如果图片存在跨域 有多种解决方案 本文仅提供图片转换base64方法 其余请自行百度

接口图片转base64

// 多张图片转base64
baseFun() {
    for (let i = 0; i < this.imgdata.length; i++) {
      arr.push(this.imgFun(this.imgdata[i]))
    }
    var that = this
    Promise.all(arr).then(() => {
      that.$nextTick(() => {
        // 转完base64触发下载 就不会图片跨域白屏
        that.downloadFun()
      })
    })
}

// 转base64
imgFun(url) {
  var that = this
  return new Promise((resolve) => {
    var xhr = new XMLHttpRequest()
    xhr.open('get', url, true)
    xhr.responseType = 'blob'
    xhr.onload = function () {
      if (this.status === 200) {
        var blob = this.response
        var fileReader = new FileReader()
        fileReader.onloadend = function (e) {
          var result = e.target.result
          that.imglist.push(result)
          resolve(result)
        }
        fileReader.readAsDataURL(blob)
      }
    }
    xhr.send()
  })
}

// 下载
downloadFun() {
  this.$nextTick(() => {
    html2canvas(this.$refs.poster_content, {
      useCORS: true,
      allowTaint: false
      // 可自定义canvas画布
      // width: 354,
      // height: 727,
      backgroundColor: 'transparent', // 设置背景透明
      dpi: window.devicePixelRatio * 4,
      scale: 4
    }).then((canvas) => {
      const dataUrl = canvas.toDataURL('image/png')
      // dataUrl 生成的图片地址
      // saveAs(dataUrl, this.img.split('/').pop())
      canvas.toBlob((blob) => { 
         const blobUrl = window.URL.createObjectURL(blob)
         // 下载
         saveAs(blobUrl)
       })
    })
  })
}

注意 如果h5不走下载走浏览器自带的长按下载 请给生成的img加禁止拖动 否则部分浏览器拖动会和浏览器长按下载弹出窗互斥

// 禁止拖动 img { -webkit-user-drag: none; }

知者甚少 唯善学 共勉