在vue中使用高德地圖vue-amap

1.安裝javascript

vue-amap我安裝指定版本0.5.10的版本html

npm i --save vue-amap@0.5.10

2.main.js中的配置vue

key申請地址教程:https://lbs.amap.com/api/javascript-api/guide/abc/preparejava

// 高德離線地圖
import VueAMap from 'vue-amap';
Vue.use(VueAMap);

VueAMap.initAMapApiLoader({
  // 高德key
  key: 'd6eabbd08f89ccfb74278b36ab6342567', // 本身到官網申請,我隨便寫的
  // 插件集合 (插件按需引入)
  plugin: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.CircleEditor', 'AMap.MarkerClusterer'],
  v: '1.4.15', // 我也不知道爲何要寫這個,不寫項目會報錯,並且我隨便寫的,跟我下載的版本對應不了
  uiVersion: '1.0.11' // ui版本號,也是須要寫
})

3.需求web

在地圖初始化的時候顯示每一個省內項目的個數以及省份的名字,畫一條到莫斯科的路徑。信息以下圖。npm

經過監聽鼠標的滾動放大縮小事件,放大後顯示具體的信息以下圖:api

 

 

4.項目中的應用數組

 注意:若是同一個頁面要使用多個高德地圖vid不能相同ide

<template>
<div>
   <el-amap vid="amapPro" 
    :amap-manager="amapManager"
    :mapStyle="mapStyle"
    :zoom="zoom"
    :events="events"
    :resizeEnable="resizeEnable"
    >
    </el-amap>
</div>
</template>

js部分oop

<script>
import {AMapManager, lazyAMapApiLoaderInstance} from 'vue-amap'
let amapManager = new AMapManager() // 新建生成地圖畫布

export default {
  data () {
    let self = this
    return {
      // ------------高德地圖參數開始-----------------
      resizeEnable: true, //是否監控地圖容器尺寸變化
      zoom: 4, // 設置初始化級別
      mapStyle: 'amap://styles/33ac9bd25289b5229362e1f52b481f49', // 使用的自定義地圖樣式,能夠根據需求顯示/隱藏內容,改變主題顏色等,具體的使用下面會寫
      amapManager,
      events: {
        init (o) {
          lazyAMapApiLoaderInstance.load().then(() => {
            self.initPage() // 初始化數據self指向this
            self.changeMap() // 綁定鼠標縮放事件
            self.setLine() // 畫一條北京到莫斯科的路線
          })
        },
      },
      // ------------高德地圖參數結束----------------
    }
  },
  methods: {
    // -----------------道德地圖開始----------
    // 道德地圖啓動頁面
    // 初始化省份和數量的數據
    initPage() {
      let markers = []
      let _this = this
      // curProData數據的格式[{city:'成都市',province: '四川省',...},{city:'XX市',province: '湖南省',...},{city:'XX市',province: '四川省',...}]
      // let curProData: [{        
      //   province: "四川省",
      //   city: "成都市",
      //   county: "金牛區",
      //   labelOffset: [0, -12],
      //   lat: 30.705218, // 經度
      //   lng: 104.058201, // 緯度,
      //   state: 1
      // },{...}]
      let provinceData = _this.curProData // 當前項目數據 
      let obj = this.getWordCntMap(provinceData) // obj的格式,經過getWordCntMap方法獲得{'四川省': 2,'湖南省': 3,....}
      let map = _this.amapManager.getMap()
      map.clearMap() // 清除全部的覆蓋物信息
      // 繪畫省份的點和數量
      AMapUI.loadUI(['overlay/SimpleMarker'], function (SimpleMarker) {
        for (let key in obj) {
          markers.push(
            new SimpleMarker({
              zIndex: 50,
              iconLabel: '<div class="mapIcon" style=""><span class="mapIcon_title">' + key + '</span><span class="mapIcon_num">' + obj[key] + '</span></div>',
              //直接設置html(須要以"<"開頭而且以">"結尾)
              iconStyle: '',
              //設置基點偏移
              offset: new AMap.Pixel(-10, -60), // 偏移
              map: map,
              showPositionPoint: true, // 定位點
              position: _this.geoProvince[key] // geoProvince裏面是省份的經緯度:例如geoProvince: {'四川省': [104.10194, 30.65984],...}
            })
          )
        }
      })
    },
    // 繪製路徑
    setLine() {
      let map = this.amapManager.getMap()
      AMapUI.loadUI(['misc/PathSimplifier'], function(PathSimplifier) {
        if (!PathSimplifier.supportCanvas) {
          alert('當前環境不支持 Canvas!');
          return;
        }
        var pathSimplifierIns = new PathSimplifier({
            zIndex: 100,
            autoSetFitView: false,
            map: map, // 所屬的地圖實例
            getPath: function(pathData, pathIndex) {
              return pathData.path;
            },
            getHoverTitle: function(pathData, pathIndex, pointIndex) {
              if (pointIndex >= 0) {
                //point 
                return pathData.name + ',點:' + pointIndex + '/' + pathData.path.length;
              }
              return pathData.name + ',點數量' + pathData.path.length;
            },
            renderOptions: {
              renderAllPointsIfNumberBelow: -1 // 繪製路線節點,如不須要可設置爲-1
            }
          });
          // 設定數據源數組,並觸發從新繪製。data爲空時將清除顯示內容。 
          pathSimplifierIns.setData([{
            name: '北京-莫斯科 線路',
            path: [
              [116.405289, 39.904987],
              [37.35, 55.45]
            ]
          }]);
          // pathSimplifierIns.render()
          //對第一條線路(即索引 0)建立一個巡航器
          var navg1 = pathSimplifierIns.createPathNavigator(0, {
            loop: true, // 循環播放
            speed: 1050000 // 巡航速度,單位公里/小時
          });
          navg1.start();
      });
    },
    // 初始化放大後項目的數據
    initPro() {
      let markers = []
      let _this = this
      // curProData數據的格式[{city:'成都市',province: '四川省',...},{city:'XX市',province: '湖南省',...},{city:'XX市',province: '四川省',...}]
      // let curProData: [{        
      //   province: "四川省",
      //   city: "成都市",
      //   county: "金牛區",
      //   labelOffset: [0, -12],
      //   lat: 30.705218, // 經度
      //   lng: 104.058201, // 緯度,
      //   state: 1
      // },{...}]
      let provinceData = _this.curProData // 省份數據
      let map = _this.amapManager.getMap()
      map.clearMap()
      AMapUI.loadUI(['overlay/SimpleMarker'], function (SimpleMarker) {
        let color = ['#00F04F', '#01DAFF', '#0098E9', '#F3A100', '#F7666A', '#FCE800']
        // 已接入,波紋圓圈藍色/黃色 0.1.2.3
        // 未接入 4.5
        provinceData.forEach(element => {
          if (element.lng && element.lat) {
            markers.push(
              new SimpleMarker({
                // 定位點的樣式
                showPositionPoint: {
                  color: element['state'] == 5 || element['state'] == 4 ? color[element['state']] : 'rgba(255,255,255,0)',
                  radius: element['state'] == 5 || element['state'] == 4 ? 5 : 0
                },
                // 自定義定位點,波紋感的圓點
                iconLabel: `${(element['state'] !== 4 && element['state'] !== 5) ? '<div class="example"><span class="dot colorStyle'+ element.state +'"></span></div>' : ''}`,               
                //直接設置html(須要以"<"開頭而且以">"結尾)
                map: map,
                position: [element.lng, element.lat], // 經緯度
                // 定位點的label標籤
                label: {
                    offset: element['labelOffset'] ? new AMap.Pixel(+element['labelOffset'][0], +element['labelOffset'][1]) : '', // 修改label相對於marker的位置
                    // offset: new AMap.Pixel(0,0), // 修改label相對於marker的位置
                    content: '<div class="makerLabel"><span class="mapIcon_title" style="color:' + color[element['state']] + '">' + element.name + '</span></div>'
                },
              })
            )
          }
          
        });
      })
    },
    // 綁定高德地圖放大縮小map事件
    changeMap() {
      let map = this.amapManager.getMap()
      map.on('zoomchange',() => {
        var zoom = map.getZoom(); //獲取當前地圖級別
        if (zoom >= 6) {
          this.initPro()
        } else {
          this.initPage()
        }
      });
    },
    // 根據省份計算重複的個數
    getWordCntMap (arr) {
      let arrData = arr
      let obj = {}
      for (let i = 0; i < arrData.length; i++) {
        if (arrData[i].lat) {
          var item = arrData[i].province // province爲計算的屬性,可換成你想計算的重複個數的屬性名字
          obj[item] = (obj[item] + 1) || 1
        }
      }
      return obj
    },
    // -----------------道德地圖結束----------
  },
  created () {
    this.addprojects() // 請求項目數據詳情
  },
  watch: {
    // 個人頁面上有下拉選項.根據選擇的選項從新渲染map數據
    // 舉個列子數據格式以下
    // let levelData = [{
    //   level10: [{        
    //     province: "四川省",
    //     city: "成都市",
    //     county: "金牛區",
    //     labelOffset: [0, -12],
    //     lat: 30.705218, // 經度
    //     lng: 104.058201, // 緯度,
    //     state: 1
    //   },{...}],
    //   level12: [{        
    //     province: "四川省",
    //     city: "瀘州市",
    //     county: "CC區",
    //     labelOffset: [0, -12],
    //     lat: 30.705218, // 經度
    //     lng: 104.058201, // 緯度,
    //     state: 1
    //   },{...}],
    //   level15: [{        
    //     province: "河南省",
    //     city: "保定市",
    //     county: "XX區",
    //     labelOffset: [0, -12],
    //     lat: 30.705218, // 經度
    //     lng: 104.058201, // 緯度,
    //     state: 1
    //   },{...}],
    //   other15: [{        
    //     province: "湖南省",
    //     city: "長沙市",
    //     county: "XX區",
    //     labelOffset: [0, -12],
    //     lat: 30.705218, // 經度
    //     lng: 104.058201, // 緯度,
    //     state: 1
    //   },{...}]      
    // }]
    // 監聽等級數據改變
    levelSize(cul) {
      switch(+cul) {
        case 0:
        this.curProData = this.levelData.level10; 
        break
        case 1:
        this.curProData = this.levelData.level12;
        break
        case 2:
        this.curProData = this.levelData.level15;
        break
        case 3:
        this.curProData = this.levelData.other15;
        break
        case 4:
        this.curProData = this.projects;
        break
        default: 
        this.curProData = this.projects
      }
      this.initPage()
      const map = this.amapManager.getMap();
      map.setZoom(4) // 重置地圖的級別
    },
  },
}
</script>

樣式:主要是波紋的定位點

<style>
/* 初始化定位標籤樣式 */
.amap-marker-label{
  vertical-align: middle;
  color: #555;
  background-color: #fffeef;
  font-size: 12px;
  white-space: nowrap;
  border: 1px solid #8e8e8e;
  width: auto;
  border-radius: 5px 5px 5px 0;
}
.mapIcon{
  vertical-align: middle;
  color: #555;
  background-color: #fffeef;
  font-size: 12px;
  white-space: nowrap;
  position: relative;
  border: 1px solid #8e8e8e;
  width: auto;
  border-radius: 5px 5px 5px 0;
  height: 23px;
  line-height: 23px;
  top: 25px;
  left: -6px;
}
.mapIcon_title{
  padding: 5px;
  border-radius: 5px 0 0 0;
}
.mapIcon_num{
  padding: 0 5px;
  display: inline-block;
  height: 100%;
  color: #fff;
  background-color: #dc3912;
  border-radius: 0 5px 5px 0;
}
.mapIcon:before,
.mapIcon:after{
  content: '';
  display: block;
  position: absolute;
  width: 0;
  height: 0;
  border: solid rgba(0,0,0,0);
  border-width: 6px;
  left: 9px;
}
.mapIcon:before{  
  bottom: -13px;
  border-top-color: #8e8e8e;
}
.mapIcon:after{
  bottom: -12px;
  border-top-color: #fffeef;
}
.amap-simple-marker-label{
  display: inline-flex;
}
/* 波紋圓圈 */
.example {
  position: absolute;
  top: 25px;
  left: 2px;
}
.dot{
  display: inline-block;
}
/* 顏色 */
/* let color = ['#00F04F', '#01DAFF', '#0098E9', '#F3A100', '#F7666A', '#FCE800'] */
.colorStyle0:before,
.colorStyle0:after{
  background-color: #00F04F;
}

.colorStyle1:before,
.colorStyle1:after{
  background-color: #01DAFF;
}

.colorStyle2:before,
.colorStyle2:after{
  background-color: #0098E9;
}

.colorStyle3:before,
.colorStyle3:after{
  background-color: #F3A100;
}

.colorStyle4:before,
.colorStyle4:after{
  background-color: #F7666A;
}

.colorStyle5:before,
.colorStyle5:after{
  background-color: #FCE800;
}

.colorStyle0:after{
  box-shadow: 0 0 10px rgba(0,240,79,.3) inset;
}
.colorStyle1:after{
  box-shadow: 0 0 10px rgba(1,218,255,.3) inset;
}
.colorStyle2:after{
  box-shadow: 0 0 10px rgba(0,152,233,.3)inset;
}
.colorStyle3:after{
  box-shadow: 0 0 10px rgba(243,161,0,.3) inset;
}
.colorStyle4:after{
  box-shadow: 0 0 10px rgba(247,102,106,.3) inset;
}
.colorStyle5:after{
  box-shadow: 0 0 10px rgba(252,232,0,.3) inset;
} 
.dot:before{
  content:' ';
  position: absolute;
  z-index:2;
  left:0;
  top:0;
  width:12px;
  height:12px; 
  /* background-color: #ff4200; */
  border-radius: 50%;
}

.dot:after {
  content:' ';
  position: absolute;
  z-index:1;
  width:12px;
  height:12px; 
  /* background-color: #ff4200; */
  border-radius: 50%;
  /* box-shadow: 0 0 10px rgba(0,0,0,.3) inset; */
  -webkit-animation-name:'ripple';/*動畫屬性名,也就是咱們前面keyframes定義的動畫名*/
  -webkit-animation-duration: 1.5s;/*動畫持續時間*/
  -webkit-animation-timing-function: ease; /*動畫頻率,和transition-timing-function是同樣的*/
  -webkit-animation-delay: 0s;/*動畫延遲時間*/
  -webkit-animation-iteration-count: infinite;/*定義循環資料,infinite爲無限次*/
  -webkit-animation-direction: normal;/*定義動畫方式*/
}
@keyframes ripple {
   0% {
    left:6px;
    top:6px;
    opcity:85;
    width:0;
    height:0;
  }
  100% {
    left:-14px;
    top:-14px;
    opacity: 0;
    width:40px;
    height:40px;
  }
}
</style>

附:

使用自定義地圖:

1.申請key,上面附了申請方法的連接

 

 

2. 建立模板,選擇一個模板後點建立就能夠了,而後再根據本身的需求選擇須要顯示的東西。

 

保存和發佈,保存發佈了才能使用

 

 

 點擊複製,把樣式id複製到項目的mapStyle便可

相關文章
相關標籤/搜索