MapVGL的基本使用和定制不同图标显示

基本需求:

需要绘制地图、并显示大量的点和标签,同时点和标签的图标需要区分、点击点弹窗显示信息

所以使用MapVGL

MapVGL的基本使用方法:

文档地址:MapVGL | 快速入门 (baidu.com)

Vue中使用方法:

1、首先注册百度AK

2、index.html中引入相关js

  <!-- 百度地图基础库 使用自己的 ak 进行配置 -->
       <script type="text/javascript"
            src="https://api.map.baidu.com/api?v=3.0&type=webgl&ak=********"></script>
    <!-- 公共的文件代码 里面包含 地图初始化 和 实用样式 -->
    <script src="https://mapv.baidu.com/gl/examples/static/common.js"></script>
    <!-- 使用根据城市名称获取城市的坐标 -->
    <script src="https://mapv.baidu.com/build/mapv.min.js"></script>
    <!--使用mapcgl的时候需要引入-->
    <script src="https://code.bdstatic.com/npm/mapvgl@1.0.0-beta.146/dist/mapvgl.min.js"></script></script>

3、在common.js 中有初始化地图公共的代码,但是其将地图容器的名称固定的写为 map_container,这里需要注意。

<div id="map_container"></div>

4、初始化 方法  

initMap()

效果

完整代码

<template>
  <div class="home">
    <div id="map_container"></div>
  </div>
</template>

<script>
// @ is an alias to /src
/* eslint-disable */
export default {
  name: 'HomeView',
  components: {},
  mounted () {
    this.initMap()
  },
  methods: {
    initMap () {
      var map = initMap({
        tilt: 60,
        heading: 0,
        center: [109.792816, 27.702774],
        zoom: 5,
        style: whiteStyle,
        skyColors: [
          // 地面颜色
          'rgba(226, 237, 248, 0)',
          // 天空颜色
          'rgba(186, 211, 252, 1)'
        ]
      })

      var data = []

      var citys = [
        '北京', '天津', '上海', '重庆', '石家庄', '太原', '呼和浩特', '哈尔滨',
        '长春', '沈阳', '济南', '南京', '合肥', '杭州', '南昌', '福州', '郑州',
        '武汉', '长沙', '广州', '南宁', '西安', '银川', '兰州', '西宁', '乌鲁木齐',
        '成都', '贵阳', '昆明', '拉萨', '海口'
      ]
      var markers = [
        'images/marker.png',
        'images/icons/icon-accident.png',
        'images/icons/icon-airplane.png',
        'images/icons/icon-location.png',
        'images/icons/label-accident.png',
        'images/icons/label-jam.png',
        'images/icons/label-warning.png',
      ]

      var randomCount = 100

      // 构造数据
      while (randomCount--) {
        var cityCenter = mapv.utilCityCenter.getCenterByCityName(citys[parseInt(Math.random() * citys.length, 10)])
        data.push({
          geometry: {
            type: 'Point',
            coordinates: [cityCenter.lng - 2 + Math.random() * 4, cityCenter.lat - 2 + Math.random() * 4]
          },
          // properties: {
          //     icon: markers[Math.floor(Math.random() * markers.length)]
          // }
        })
      }

      var view = new mapvgl.View({
        map: map
      })

      var layer = new mapvgl.IconLayer({
        width: 100 / 4,
        height: 153 / 4,
        offset: [0, -153 / 8],
        opacity: 0.8,
        icon: require('../assets/address.png'),
        enablePicked: true, // 是否可以拾取
        selectedIndex: -1, // 选中项
        selectedColor: '#ff0000', // 选中项颜色
        autoSelect: true, // 根据鼠标位置来自动设置选中项
        onClick: (e) => { // 点击事件
          console.log('click', e)
        },
        onDblClick: e => {
          console.log('double click', e)
        },
        onRightClick: e => {
          console.log('right click', e)
        }
      })
      view.addLayer(layer)
      layer.setData(data)

      map.setDefaultCursor('default')

    }
  }
}
</script>
<style lang="less" scoped>
// 父级一定要给宽高,不然无法显示
.home {
  width: 100%;
  height: 100%;

  #map_container {
    width: 100%;
    height: 100%;
  }
}
</style>

自定义icon和标签实现思路:

使用malvgl中的IconLayer和LabelLayer

自定义样式并增加点击事件,创建弹窗

// 点图层样式
      _this.iconLayerOption = {
        width: 13,
        height: 14,
        enablePicked: true, // 是否可以拾取
        selectedIndex: -1, // 选中项
        autoSelect: false, // 根据鼠标位置来自动设置选中项
        onClick: (e) => { // 点击事件
          console.log(e)
          if (e.dataItem) {
            _this.infoWindowObject = new BMapGL.InfoWindow(_this.createWindowHtml(e.dataItem.geometry), {
              title: '',
              width: 300
            })
            let point = new BMapGL.Point(e.dataItem.geometry.coordinates[0], e.dataItem.geometry.coordinates[1]);
            _this.map.openInfoWindow(_this.infoWindowObject, point)
          }
        }
      }
// 标签图层样式
      _this.labelLayerOption = {
        textAlign: 'center',
        offset: [0, -5],
        padding: [2, 5],
        borderRadius: 5,
        width: 100,
        overflow: 'hidden',
        fontSize: 8,
        lineHeight: 12,
        collides: true, // 是否开启碰撞检测, 数量较多时建议打开
        enablePicked: true,
        onClick: (e) => { // 点击事件
          if (e.dataItem) {
            _this.infoWindowObject = new BMapGL.InfoWindow(_this.createWindowHtml(e.dataItem.geometry), {
              title: '',
              width: 300
            })
            let point = new BMapGL.Point(e.dataItem.geometry.coordinates[0], e.dataItem.geometry.coordinates[1]);
            _this.map.openInfoWindow(_this.infoWindowObject, point)
          }
        }
      }

获取数据后,循环渲染点和标签

if (_this.view) {
        // 删除所有可视化图层
        _this.view.removeAllLayers()
      }




const layer1 = new mapvgl.IconLayer(Object.assign(_this.iconLayerOption, {
          icon: _this.icons[0]
        }))
        const layer11 = new mapvgl.LabelLayer(Object.assign(_this.labelLayerOption, {
          textColor: '#fff',
          borderColor: _this.labelColors[0],
          backgroundColor: _this.labelColors[0]
        }))
        _this.view.addLayer(layer1)
        _this.view.addLayer(layer11)
        layer1.setData(data1)
        layer11.setData(data1)

弹窗方法

createWindowHtml(item) {
      let _this = this
      // 点击出窗口
      const html = `
        <div class="window-content">
            <div class="window-content-top">
              <img src="${item.imgUrl ? item.imgUrl : _this.imageUrl}" alt="">
              <div class="top-content">
                <div class="top-title line-two-ellipsis">${item.name}</div>
                <div class="top-title-btn">
                  <span ontouchend="window.goMap('${item['coordinates'][1]}','${item['coordinates'][0]}','${item.address}','${item.name}')">
                    <span class="top-btn-text" style="color: #2495E8"><img style="width: 20px;height: 20px" src="${_this.daohangicon}">一键导航</span>
                  </span>
                  <span class="top-btn-text" style="color: #2495E8" id="btn_detail" ontouchend="window.companyDetail('${item.id}')">查看详情 >> </span>
                </div>
              </div>
            </div>
            <div class="window-bottom">
              <img src="${_this.addressIcon}" alt="">
              <span>地址:${item.address}</span>
            </div>
            <div class="window-bottom">
              <img src="${_this.phoneIcon}" alt="">
              <span>类型:${_this.getValue(_this.tabsCompanyCate, item.type1)}</span>
            </div>
          </div>`
      return html
    },

附一份完成参考代码:

<template>
  <div class="wechat-company-map1">
    <div v-if="showList" class="company-map1-header">
      <!--      <div @click="closeAllDialog">关闭弹窗</div>-->
      <van-search v-model="queryData.keyword" placeholder="请输入关键词搜索" @change="onSearch"/>
      <div class="company-title">
      <span v-for="(item, index) in tabsFour" :key="index" class="wrap-item"
            :class="index === currentTabIndex ? 'wrap-item-active': ''"
            @click="changeTab(index, item.dictValue)">
            <img :src="icons[index]" alt="">
            <span>{{ item.dictLabel }}</span>
        </span>
      </div>
      <!--      街道类型-->
      <van-dropdown-menu active-color="#005ABF">
        <van-dropdown-item v-model="queryData.street" :options="tabsStreet" @change="onSearch"/>
        <van-dropdown-item v-model="queryData.type1" :options="tabsCompanyCate" @change="onSearch"/>
      </van-dropdown-menu>
    </div>
    <div class="company-map">
      <div id="allmapF" ref="allmap"></div>
    </div>
    <!--    <div class="back1" @click="showList = !showList">
          <i :class="showList?'el-icon-map-location': 'el-icon-menu'"></i>
          <span>{{ showList ? '地图' : '列表' }}</span>
        </div>-->
    <div class="back1" @click="toList">
      <i class="el-icon-menu"></i>
      <span>列表</span>
    </div>
    <div class="back" @click="goback">返回</div>
    <!-- baidu-map 用来初始化 没有用处 防止BMap找不到-->
    <!--    <baidu-map :zoom="14" @ready="initMap" style="height:0" :scroll-wheel-zoom="true"></baidu-map>-->
  </div>
</template>

<script>
/* eslint-disable */
import './assets/scss/_wechat.scss'
// import MyOverlay from './components/myOverla'
import wx from 'weixin-js-sdk'

export default {
  name: 'CompanyMap1',
  components: {
    // MyOverlay
  },
  data() {
    return {
      showList: true,
      clickTab: '',
      imageUrl: require('./assets/images/thumb.png'),
      shopImg: require('./assets/images/map-icon-0.png'),
      infoWindow: {
        id: '',
        imgUrl: '',
        title: '',
        address: '',
        cate: '',
        lng: '',
        lat: '',
        show: false
      },
      queryData: {
        keyword: '',
        page: 1,
        limit: 1000,
        street: '',
        type1: '',
        slType: ''
      },
      userForm: {
        nickName: '',
        openId: '',
        HeadImgUrl: ''
      },
      tabsStreet: [{text: '企业所在区域', value: ''}],
      tabsCompanyCate: [{text: '企业所属类型', value: ''}],
      tabsFour: [],
      list: [],
      showLoading: false,
      currentTabIndex: '',
      points: [],
      active: false,
      icons: [require('./assets/images/map-icon-0.png'), require('./assets/images/map-icon-1.png'), require('./assets/images/map-icon-2.png'), require('./assets/images/map-icon-3.png'), require('./assets/images/ico-address1.png')],
      labelColors: ['#142F9B', '#721AA4', '#14973A', '#BC427B', '#721AA4'],
      bgs: [require('./assets/images/map-bg-0.png'), require('./assets/images/map-bg-1.png'), require('./assets/images/map-bg-2.png'), require('./assets/images/map-bg-3.png')],
      showPopover: false,
      center: {lng: '118.10303', lat: '37.15088'},
      map: '',
      layer1: null,
      view: null,
      iconLayerOption: null,
      iconUserLayerOption: null,
      labelLayerOption: null,
      windowInfoHtml: null,
      infoWindowObject: null,
      addressIcon: require('./assets/images/address.png'),
      phoneIcon: require('./assets/images/icon-cate.png'),
      daohangicon: require('./assets/images/daohang.png'),
      latitude: '',
      longitude: ''
    }
  },
  mounted() {
    let _this = this
    _this.getAccessToken()
    _this.getUserLocation()
    // _this.getWechatCode()
    document.title = this.$route.meta.title
    // this.initMap()
    window.companyDetail = (id) => {
      _this.toCompanyDetail(id)
      Event.stopPropagation()
    }
    window.getlocation = function (obj) {
      let tt = [obj.lat, obj.lng] // 未转化坐标
      wx.ready(() => {
        wx.openLocation({
          longitude: parseFloat(tt[1]), // 经度,浮点数,范围为180 ~ -180。
          latitude: parseFloat(tt[0]), // 纬度,浮点数,范围为90 ~ -90
          name: obj.name, // 位置名
          address: obj.location, // 地址详情说明
          scale: 16 // 地图缩放级别,整形值,范围从1~28。默认为最大
        })
      })
    }
    window.goMap = function (lat, lng, location, name) {
      let obj = {
        lat, lng, name, location
      }
      getlocation(obj)
    }
  },
  created() {
    this.init()
  },
  destroyed() {
    if (this.view) {
      this.view.removeAllLayers()
    }
    /**
     * 销毁百度地图
     */
    try {
      // 注销地图(换成你初始化时定义的地图变量)
      this.map = null
      // 获取interval的最高ID然后遍历清除
      const HIGHEST_INTERVAL_ID = setInterval(';')
      for (let i = 0; i < HIGHEST_INTERVAL_ID; i++) {
        clearInterval(i)
      }
      // 获取百度地图创建的DOM并销毁
      const BAIDU_MAPS = document.querySelectorAll('.tangram-suggestion-main')
      BAIDU_MAPS.forEach((item) => {
        document.body.removeChild(item)
      })
    } catch (e) {
      console.log(e)
    }
  },
  methods: {
    toList() {
      this.$router.push('/wechatCompany')
    },
    // 定位用户位置信息
    getUserLocation() {
      let _this = this
      // 测试
      // _this.$nextTick(() => {
      //   _this.lng = 117.995000
      //   _this.lat = 37.360061
      //   _this.initMap(_this.lng, _this.lat)
      // })
      wx.ready(() => {
        wx.getLocation({
          // type: 'wgs84', // 默认为wgs84的 gps 坐标,如果要返回直接给 openLocation 用的火星坐标,可传入'gcj02'
          success: function (res) {
            _this.lng = _this.qqMapToBMap(res.longitude, res.latitude)[0]
            _this.lat = _this.qqMapToBMap(res.longitude, res.latitude)[1]
            // _this.latitude = res.latitude // 纬度,浮点数,范围为90 ~ -90
            // _this.longitude = res.longitude // 经度,浮点数,范围为180 ~ -180。
            // let speed = res.speed; // 速度,以米/每秒计
            // let accuracy = res.accuracy; // 位置精度
            // alert(_this.latitude)
            // alert(_this.longitude)
            _this.$nextTick(() => {
              _this.initMap(_this.lng, _this.lat)
            })
          }
        });
        // wx.openLocation({
        //   longitude: parseFloat(tt[1]), // 经度,浮点数,范围为180 ~ -180。
        //   latitude: parseFloat(tt[0]), // 纬度,浮点数,范围为90 ~ -90
        //   name: obj.name, // 位置名
        //   address: obj.location, // 地址详情说明
        //   scale: 16 // 地图缩放级别,整形值,范围从1~28。默认为最大
        // })
      })
    },
    qqMapToBMap(lng, lat) {
      if (lng === null || lng === '' || lat === null || lat === '') {
        return [lng, lat]
      }
      let x_pi = 3.14159265358979324
      let x = parseFloat(lng)
      let y = parseFloat(lat)
      let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi)
      let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi)
      let lng1 = (z * Math.cos(theta) + 0.0065).toFixed(5)
      let lat1 = (z * Math.sin(theta) + 0.006).toFixed(5)
      return [lng1, lat1]
    },
    initMap(lang, lat) {
      this.drawMap(lang, lat, this.getList())
    },
    // 绘制地图
    drawMap(lang, lat, callback) {
      let _this = this
      // 创建Map实例
      _this.map = new BMapGL.Map('allmapF')
      _this.map.centerAndZoom(new BMapGL.Point(lang, lat), 16)
      // 开启鼠标滚轮缩放
      _this.map.enableScrollWheelZoom(true)
      _this.view = new mapvgl.View({
        map: _this.map
      })
      // 点图层样式
      _this.iconLayerOption = {
        width: 13,
        height: 14,
        enablePicked: true, // 是否可以拾取
        selectedIndex: -1, // 选中项
        autoSelect: false, // 根据鼠标位置来自动设置选中项
        onClick: (e) => { // 点击事件
          console.log(e)
          if (e.dataItem) {
            _this.infoWindowObject = new BMapGL.InfoWindow(_this.createWindowHtml(e.dataItem.geometry), {
              title: '',
              width: 300
            })
            let point = new BMapGL.Point(e.dataItem.geometry.coordinates[0], e.dataItem.geometry.coordinates[1]);
            _this.map.openInfoWindow(_this.infoWindowObject, point)
          }
        }
      }
      // 标签图层样式
      _this.labelLayerOption = {
        textAlign: 'center',
        offset: [0, -5],
        padding: [2, 5],
        borderRadius: 5,
        width: 100,
        overflow: 'hidden',
        fontSize: 8,
        lineHeight: 12,
        collides: true, // 是否开启碰撞检测, 数量较多时建议打开
        enablePicked: true,
        onClick: (e) => { // 点击事件
          if (e.dataItem) {
            _this.infoWindowObject = new BMapGL.InfoWindow(_this.createWindowHtml(e.dataItem.geometry), {
              title: '',
              width: 300
            })
            let point = new BMapGL.Point(e.dataItem.geometry.coordinates[0], e.dataItem.geometry.coordinates[1]);
            _this.map.openInfoWindow(_this.infoWindowObject, point)
          }
        }
      }
      if (callback) callback()
    },
    // [2022.5.16 只显示一层]
    /*drawPoints(data) {
      let _this = this
      if (_this.view) {
        // 删除所有可视化图层
        _this.view.removeAllLayers()
      }
      const showData = []
      console.log(this.queryData.slType)
      data.forEach(item => {
        showData.push({
          geometry: {
            id: item.id,
            name: item.name,
            address: item.address,
            imgUrl: item.imgUrl,
            type1: item.type1,
            type: 'Point',
            coordinates: [item.lng, item.lat]
          },
          properties: {
            text: item.name.length > 10 ? item.name.slice(0, 10) + '\n' + item.name.slice(10, item.name.length) : item.name // 展示的文字
          }
        })
      })
      if (showData.length > 0) {
        const layer = new mapvgl.IconLayer(Object.assign(_this.iconLayerOption, {
          icon: _this.icons[_this.currentTabIndex]
        }))
        const layer1 = new mapvgl.LabelLayer(Object.assign(_this.labelLayerOption, {
          textColor: '#fff',
          borderColor: _this.labelColors[_this.currentTabIndex],
          backgroundColor: _this.labelColors[_this.currentTabIndex]
        }))
        _this.view.addLayer(layer)
        _this.view.addLayer(layer1)
        layer.setData(showData)
        layer1.setData(showData)
      }
    },*/
    // 绘制点 [2022.5.15 思路 实现四企业全部显示的功能,新建四个图层,首次加载没问题,返回加载会出现弹窗无法关闭的bug,所以改成只显示一层]
    drawPoints(data) {
      let _this = this
      if (_this.view) {
        // 删除所有可视化图层
        _this.view.removeAllLayers()
      }
      const layer = new mapvgl.IconLayer({
        width: 10,
        height: 13,
        enablePicked: true, // 是否可以拾取
        selectedIndex: -1, // 选中项
        autoSelect: false, // 根据鼠标位置来自动设置选中项
        icon: _this.icons[4],
        data: [
          {
            geometry: {
              type: 'Point',
              coordinates: [_this.lng, _this.lat]
            }
          }
        ]
      })
      _this.view.addLayer(layer)
      let data1 = []
      let data2 = []
      let data3 = []
      let data4 = []
      data.forEach(item => {
        switch (parseInt(item['slType'])) {
          case 1:
            data1.push({
              geometry: {
                id: item.id,
                name: item.name,
                address: item.address,
                imgUrl: item.imgUrl,
                type1: item.type1,
                type: 'Point',
                coordinates: [item.lng, item.lat]
              },
              properties: {
                text: item.name.length > 10 ? item.name.slice(0, 10) + '\n' + item.name.slice(10, item.name.length) : item.name // 展示的文字
              }
            })
            break
          case 2:
            data2.push({
              geometry: {
                id: item.id,
                name: item.name,
                address: item.address,
                imgUrl: item.imgUrl,
                type1: item.type1,
                type: 'Point',
                coordinates: [item.lng, item.lat]
              },
              properties: {
                text: item.name.length > 10 ? item.name.slice(0, 10) + '\n' + item.name.slice(10, item.name.length) : item.name // 展示的文字
              }
            })
            break
          case 3:
            data3.push({
              geometry: {
                id: item.id,
                name: item.name,
                address: item.address,
                imgUrl: item.imgUrl,
                type1: item.type1,
                type: 'Point',
                coordinates: [item.lng, item.lat]
              },
              properties: {
                text: item.name.length > 10 ? item.name.slice(0, 10) + '\n' + item.name.slice(10, item.name.length) : item.name // 展示的文字
              }
            })
            break
          case 4:
            data4.push({
              geometry: {
                id: item.id,
                name: item.name,
                address: item.address,
                imgUrl: item.imgUrl,
                type1: item.type1,
                type: 'Point',
                coordinates: [item.lng, item.lat]
              },
              properties: {
                text: item.name.length > 10 ? item.name.slice(0, 10) + '\n' + item.name.slice(10, item.name.length) : item.name // 展示的文字
              }
            })
            break
        }
      })
      if (data1.length > 0) {
        const layer1 = new mapvgl.IconLayer(Object.assign(_this.iconLayerOption, {
          icon: _this.icons[0]
        }))
        const layer11 = new mapvgl.LabelLayer(Object.assign(_this.labelLayerOption, {
          textColor: '#fff',
          borderColor: _this.labelColors[0],
          backgroundColor: _this.labelColors[0]
        }))
        _this.view.addLayer(layer1)
        _this.view.addLayer(layer11)
        layer1.setData(data1)
        layer11.setData(data1)
      }
      if (data2.length > 0) {
        const layer2 = new mapvgl.IconLayer(Object.assign(_this.iconLayerOption, {
          icon: _this.icons[1],
        }))
        const layer22 = new mapvgl.LabelLayer(Object.assign(_this.labelLayerOption, {
          textColor: '#fff',
          borderColor: _this.labelColors[1],
          backgroundColor: _this.labelColors[1]
        }))
        _this.view.addLayer(layer2)
        _this.view.addLayer(layer22)
        layer2.setData(data2)
        layer22.setData(data2)
      }
      if (data3.length > 0) {
        const layer3 = new mapvgl.IconLayer(Object.assign(_this.iconLayerOption, {
          icon: _this.icons[2],
        }))
        const layer33 = new mapvgl.LabelLayer(Object.assign(_this.labelLayerOption, {
          textColor: '#fff',
          borderColor: _this.labelColors[2],
          backgroundColor: _this.labelColors[2]
        }))
        _this.view.addLayer(layer3)
        _this.view.addLayer(layer33)
        layer3.setData(data3)
        layer33.setData(data3)
      }
      if (data4.length > 0) {
        const layer4 = new mapvgl.IconLayer(Object.assign(_this.iconLayerOption, {
          icon: _this.icons[3],
        }))
        const layer44 = new mapvgl.LabelLayer(Object.assign(_this.labelLayerOption, {
          textColor: '#fff',
          borderColor: _this.labelColors[3],
          backgroundColor: _this.labelColors[3]
        }))
        _this.view.addLayer(layer4)
        _this.view.addLayer(layer44)
        layer4.setData(data4)
        layer44.setData(data4)
      }
    },
    closeAllDialog() {
      // this.map.openInfoWindow(_this.infoWindowObject, point)
      console.log('close')
      this.map.closeInfoWindow(this.infoWindowObject)
    },
    createWindowHtml(item) {
      let _this = this
      // 点击出窗口
      const html = `
        <div class="window-content">
            <div class="window-content-top">
              <img src="${item.imgUrl ? item.imgUrl : _this.imageUrl}" alt="">
              <div class="top-content">
                <div class="top-title line-two-ellipsis">${item.name}</div>
                <div class="top-title-btn">
                  <span ontouchend="window.goMap('${item['coordinates'][1]}','${item['coordinates'][0]}','${item.address}','${item.name}')">
                    <span class="top-btn-text" style="color: #2495E8"><img style="width: 20px;height: 20px" src="${_this.daohangicon}">一键导航</span>
                  </span>
                  <span class="top-btn-text" style="color: #2495E8" id="btn_detail" ontouchend="window.companyDetail('${item.id}')">查看详情 >> </span>
                </div>
              </div>
            </div>
            <div class="window-bottom">
              <img src="${_this.addressIcon}" alt="">
              <span>地址:${item.address}</span>
            </div>
            <div class="window-bottom">
              <img src="${_this.phoneIcon}" alt="">
              <span>类型:${_this.getValue(_this.tabsCompanyCate, item.type1)}</span>
            </div>
          </div>`
      return html
    },
    init() {
      this.initData()
    },
    initData() {
      // 街道列表
      this.getStreet()
      // 企业类型
      this.getCompanyCate()
      // 企业列表
      // this.getList()
      // 四筛选
      this.getTabsFour()
    },
    getAccessToken() {
      // let url = window.location.href.split('#')[0]
      let _this = this
      let url = window.location.href
      this.$http.get('wxapi/getAccessToken?url=' + url).then(({data: res}) => {
        // console.log(res)
        if (res.code !== 0) {
          return
        }
        let obj = res.data
        wx.config({
          debug: false,
          appId: obj.appId,
          nonceStr: obj.noncestr,
          timestamp: obj.timestamp,
          signature: obj.sign,
          jsApiList: [
            'openLocation',
            'getLocation'
          ],
          success(res) {
            if (res.checkResult.getLocation === false) {
              alert('你的微信版本太低,不支持微信JS接口,请升级到最新的微信版本!')
            } else {
              console.log(123123)
            }
          },
          error(e) {
            console.log(e)
          }
        })
      })
    },
    // 获取微信code
    getWechatCode() {
      let _this = this
      let refreshCode = window.localStorage.getItem('refreshCode')
      let refreshDate = window.localStorage.getItem('refreshDate')
      if (refreshCode && refreshCode === 'true') {
        let now = Date.now()
        if (refreshDate && now - parseInt(refreshDate) < 10000) {
          let code = _this.getUrlParam('code')
          _this.getOpenId(code)
        } else {
          window.localStorage.setItem('refreshCode', 'true')
          window.localStorage.setItem('refreshDate', Date.now().toString())
          // 获取code
          const getCodeParams = {
            redirect_uri: encodeURIComponent(window.location.href),
            appid: 'wxf84961c6d99eef6e',
            scope: 'snsapi_userinfo'
            // state: encodeURIComponent(
            //     JSON.stringify({
            //       p: route.path,
            //     })
            // ),
          }
          // window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc7ed89709f782e35&redirect_uri=https://www.pljdxxzx.com/weixin/dist/index.html&response_type=code&scope=snsapi_userinfo&state=convenient-service'
          // window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf84961c6d99eef6e&response_type=code&scope=snsapi_userinfo&state=convenient-service&redirect_uri=http://qydt.boxing.gov.cn/#/wechatIndex.html'
          // window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf84961c6d99eef6e&response_type=code&scope=snsapi_userinfo&state=convenient-service&redirect_uri=http://qydt.boxing.gov.cn/#/wechatMap.html'
          window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${getCodeParams.appid}&redirect_uri=${getCodeParams.redirect_uri}&response_type=code&scope=${getCodeParams.scope}`;
        }
      } else {
        window.localStorage.setItem('refreshCode', 'true')
        window.localStorage.setItem('refreshDate', Date.now().toString())
        // window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc7ed89709f782e35&redirect_uri=https://www.pljdxxzx.com/weixin/dist/index.html&response_type=code&scope=snsapi_userinfo&state=convenient-service'
        // window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf84961c6d99eef6e&response_type=code&scope=snsapi_userinfo&state=convenient-service&redirect_uri=http://qydt.boxing.gov.cn/#/wechatMap.html'
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${getCodeParams.appid}&redirect_uri=${getCodeParams.redirect_uri}&response_type=code&scope=${getCodeParams.scope}&state=${getCodeParams.state}#wechat_redirect`;
      }
    },
    // 根据微信的code 获取openid
    getOpenId(code) {
      let _this = this
      let obj = {
        jsonData: '{"Code":"' + code + '"}',
        cmd: 'getwxinfo',
        UserId: 1
      }
      _this.$http.post(_this.apiUrl, obj, {emulateJSON: true}).then(function (res) {
        if (res.body.data && res.body.data.nickName) {
          _this.userForm.nickName = res.body.data.nickName
          _this.userForm.openId = res.body.data.openId
          _this.userForm.HeadImgUrl = res.body.data.HeadImgUrl
        }
      })
    },
    getUrlParam(name) {
      let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)') // 构造一个含有目标参数的正则表达式对象
      let r = window.location.search.substr(1).match(reg) // 匹配目标参数
      if (r !== null) return decodeURI(r[2])
      return null // 返回参数值
    },
    changeTab(index, value) {
      this.clickTab = index
      if (this.clickTab === this.currentTabIndex) {
        this.queryData.slType = ''
        this.currentTabIndex = ''
      } else {
        this.currentTabIndex = index
        this.queryData.slType = value
      }
      // this.currentTabIndex = index
      // this.queryData.slType = value
      this.list = []
      this.getList()
    },
    getStreet() {
      this.$http.get('/zdqy/openapi/dict', {params: {type: 'zdqy_street'}}).then(({data: res}) => {
        if (res.code === 0) {
          if (res.data.length > 0) {
            res.data.forEach(v => {
              this.tabsStreet.push({
                'text': v['dictLabel'],
                'value': v['dictValue']
              })
              this.queryData.street = this.tabsStreet[0]['value']
            })
          }
        }
      })
    },
    getCompanyCate() {
      this.$http.get('/zdqy/openapi/dict', {params: {type: 'zdqy_type'}}).then(({data: res}) => {
        if (res.code === 0) {
          if (res.data.length > 0) {
            res.data.forEach(v => {
              this.tabsCompanyCate.push({
                'text': v['dictLabel'],
                'value': v['dictValue']
              })
              this.queryData.type1 = this.tabsCompanyCate[0]['value']
            })
          }
        }
      })
    },
    getTabsFour() {
      this.$http.get('/zdqy/openapi/dict', {params: {type: 'zdqy_sl_type'}}).then(({data: res}) => {
        if (res.code === 0) {
          const data = res.data
          // data.forEach((v, i) => {
          //   v['color'] = this.colors[i]
          //   v['icon'] = this.icons[i]
          //   v['bg'] = this.bgs[i]
          // })
          this.tabsFour = data
          // 默认选择第一个
          // this.currentTabIndex = parseInt(this.tabsFour[0]['dictValue']) - 1
        }
      })
    },
    onSearch() {
      this.list = []
      this.getList()
    },
    getList() {
      // 隐藏弹窗
      this.infoWindow.show = false
      this.$http.get('/zdqy/openapi/keyEnterprises', {params: this.queryData}).then(({data: res}) => {
        if (res.code !== 0) {
          return this.showMsg(res.code, res.msg)
        }
        this.list = res.data.list
        // 画点
        this.drawPoints(this.list)
      })
    },
    // 定义弹窗内容
    choseCompany(id, item) {
      console.log(item)
      // this.center.lng = item.lng
      // this.center.lat = item.lat
      this.infoWindow.id = item.id
      this.infoWindow.title = item.name
      this.infoWindow.imgUrl = item.imageUrl
      this.infoWindow.lng = item.lng
      this.infoWindow.lat = item.lat
      this.infoWindow.address = item.address
      this.infoWindow.cate = this.getValue(this.tabsCompanyCate, item.type1)
      this.infoWindow.lat = item.lat
      this.infoWindow.show = true
      console.log(this.infoWindow)
    },
    getValue(arr, key) {
      let dataArr = arr.find(v => {
        return key === v['value']
      })
      return dataArr ? dataArr['text'] : ''
    },
    goback() {
      this.$router.push('/wechatIndex')
    },
    toCompanyDetail(id) {
      this.$router.push('/wechatDetail?id=' + id)
    },
    changeList() {
    }
  }
}
</script>

<style scoped>

</style>

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
使用百度地图中的MapVGL,可以通过以下步骤实现: 1. 从百度地图开放平台获取MapVGL的JavaScript API。 2. 在React组件中引入MapVGL的JavaScript API。 3. 在组件中设置地图容器,并创建MapVGL实例。 4. 在MapVGL实例中添加图层和数据。 以下是一个简单的React组件示例,演示如何使用百度地图中的MapVGL: ```javascript import React, { useEffect } from 'react'; import BMapGL from 'BMapGL'; import MapVGL from 'MapVGL'; const MapVGLDemo = () => { useEffect(() => { const map = new BMapGL.Map('map-container'); // 创建地图实例 map.centerAndZoom(new BMapGL.Point(116.404, 39.915), 14); // 初始化地图,设置中心点和缩放级别 const mapvgl = new MapVGL(map, { // 创建MapVGL实例 draw: 'simple', }); const layer = new MapVGL.Layer({ mapvgl, zIndex: 1, }); const geojson = { type: 'FeatureCollection', features: [{ type: 'Feature', geometry: { type: 'Point', coordinates: [116.404, 39.915], }, properties: { title: 'Marker 1', }, }], }; const dataSet = new MapVGL.DataSet(geojson); const options = { size: 20, fillStyle: 'rgba(255, 255, 0, 0.6)', shadowColor: 'rgba(255, 255, 0, 1)', }; layer.add(new MapVGL.PointLayer({ dataSet, options, })); }, []); return <div id="map-container" style={{ width: '100%', height: '600px' }} />; }; export default MapVGLDemo; ``` 在上面的示例中,我们首先引入了百度地图和MapVGL的JavaScript API,然后在组件中创建了一个地图容器,并初始化了地图实例。接着,我们创建了一个MapVGL实例,设置了绘制方式,创建了一个图层,添加了一个数据集和一个点图层,最后将图层添加到MapVGL实例中。这样就可以在React应用中使用百度地图中的MapVGL了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chenshuai5

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值