天天看點

vue使用原生高德地圖

vue使用原生高德地圖
  • 功能介紹:資訊窗體+ 資訊窗體裡的點選事件 +顯示附近的醫院和警察局+曆史軌迹
  • 都是死資料 想看的指派粘貼就行(圖檔一點要改)
  • 在index.html 中引入
<script type="text/javascript"
    src="http://webapi.amap.com/maps?v=1.4.15&key=你的key值&plugin=Map3D,AMap.DistrictLayer,AMap.Scale,AMap.ToolBar"></script>
  <script src="//webapi.amap.com/ui/1.0/main.js"></script>
           
  • 在根目錄下建立vue.config.vue 檔案
module.exports = {
  configureWebpack: {
    externals: {
      'AMap': 'AMap',
      'AMapUI': 'AMapUI'
       }
  }
};
           
  • 下面的img中的圖檔 自己要注意一下
  • 代碼如下
<template>
  <div id="Sharingrouter">
    <div id="container" ref="container"></div>
    <div id="panel"></div>
  </div>
</template>
<script>
var map;
export default {
  data() {
    return {
      aMap: null,
      infoWindow: null,
      nearbyType: "綜合醫院|衛生院|公安警察",
      userInfo: {
        studentName: "李逍遙",
        electric: "100%",
        signal: "6G",
        isOpenName: "線上",
        marchingState: "仙靈島",
        isLine: "buzhidap",
        lastUpdateTime: "現在",
        remarks: "1",
        jd: 116.397428,
        wd: 39.90923
      },
      jd: 116.397428,
      wd: 39.90923,
      //醫院,警察圖示
      police: null,
      hospital: null,
      oldLine:null,//軌迹
      //曆史軌迹資料
      list:[
        {
        P: 28.16939943249758,
Q: 113.05324226683365
        },
        {
        P: 28.16939943249758,
Q: 113.05324226683365
        },
        {
       P: 28.16939943249758,
Q: 113.05324226683365
        },
        {
          P: 28.16939943249758,
Q: 113.05324226683365
        }
      ]
    };
  },
  mounted() {
    this.init();
    this.placeSearch();
  },
  computed: {},
  created() {
    //點選标記後的彈出框
    this.infoWindow = new AMap.InfoWindow({
      offset: new AMap.Pixel(0, -40)
    });
  },
  methods: {
    init() {
      this.aMap = new AMap.Map("container", {
        resizeEnable: true,
        zoom: 12 //地圖顯示的縮放級别
      });
      // 初始化警察定位圖示
      this.police = new AMap.Icon({
        size: new AMap.Size(35, 30), //圖示大小
        image: require("../assets/img/police.png")
      });
      // 初始化醫院定位圖示
      this.hospital = new AMap.Icon({
        size: new AMap.Size(35, 30), //圖示大小
        image: require("../assets/img/hospital.png")
      });
      this.addSvgMarker();
    },
    addSvgMarker(icon, userInfo) {
      console.log("放大:");
      this.aMap.setCenter([this.jd, this.wd]);
      this.aMap.setZoom();

      let _this = this;
      // 設定高德地圖自定義UI元件
      AMapUI.loadUI(["overlay/SvgMarker"], SvgMarker => {
        //icon的取值請見  http://fontawesome.io/icons/
        if (!SvgMarker.supportSvg) {
          //目前環境并不支援SVG,此時SvgMarker會回退到父類,即SimpleMarker
          alert("目前環境不支援SVG");
        }
        //建立一個水滴狀的shape
        let shape = new SvgMarker.Shape.WaterDrop({
          height: 25, //高度
          width: 25, //不指定,維持預設的寬高比
          fillColor: "#fff" //填充色
        });
        //利用該shape建構SvgMarker
        let svgMarker = new SvgMarker(shape, {
          zIndex: 120,
          map: this.aMap,
          //經緯度
          position: new AMap.LngLat(this.jd, this.wd),
          zoomToAccuracy: true, //定位成功後是否自動調整地圖視野到定位點
          iconLabel: {
            innerHTML: `<div class="marker-layout ${
              this.userInfo.remarks === "1"
                ? "maker-layout-student"
                : "maker-layout-back"
            }"> </div>`,
            style: {
              color: "#fff"
            }
          }
        });

        this.addInfoWindow(svgMarker, userInfo);
      });
    },
    addInfoWindow(marker, userInfo) {
      // 設定marker 錨點的點選事件
      AMap.event.addListener(marker, "click", e => {
        this.infoWindow.close();
        let content = "";
        content = this.getStudentWindow(this.userInfo);
        this.infoWindow.setContent(content);
        // 錨點發生點選事件後 展開資訊框

        let _this = this;
        console.log("點選事件添加測試");
        // 設定資訊框 裡面按鈕點選事件,重點方法處
        this.infoWindow.open(this.aMap, marker.getPosition());
        // 必須在這裡添加資訊彈出框事件 如果在外面添加會導緻,資訊框裡面按鈕點選事件失效
        //obj 儲存經緯度
        var obj = marker.getPosition();
        console.log(obj);
        window.addEventListener("click", e => {
          if (e.target.id == "navigation") {
           this.mapPolyline()
            this.aMap.clearInfoWindow();
          }
        });
        // let itemClick = e => {

        // };
        // // 確定第一次點選 marker 錨點的時候回展示資訊框
        // // this.infoWindow.open(this.aMap, marker.getPosition());
        // AMap.event.addListener(marker, "click", itemClick);
      });
    },
    //建構自定義資訊窗體
    getStudentWindow(userInfo) {
      return `<div">
    <div style="padding:7px 0px 0px 0px;">
      <p class="input-item">學生姓名:${
        userInfo.studentName ? userInfo.studentName : ""
      }</p>
      <p class="input-item">電池電量:${userInfo.electric}%</p>
      <p class="input-item">信号:${userInfo.signal}</p>
      <p class="input-item">卡狀态:${
        userInfo.isOpenName ? userInfo.studentName : "暫無"
      }</p>
      <p class="input-item">定位狀态:${userInfo.marchingState}</p>
      <p class="input-item">裝置狀态:${userInfo.isLine}</p>
      <p class="input-item">更新時間:${userInfo.lastUpdateTime}</p>
      <p id="navigation" style="color:#267cfb">曆史軌迹</p>
    </div>
  </div>`;
    },
    // 搜尋周邊
    // 搜尋周邊
    placeSearch(userInfo) {
      let MSearch;
      this.aMap.plugin(
        ["AMap.PlaceSearch", "AMap.Geocoder", "AMap.ToolBar", "AMap.Scale"],
        () => {
          this.aMap.addControl(new AMap.ToolBar());
          this.aMap.addControl(new AMap.Scale());

          let geocoder = new AMap.Geocoder({
            // city 指定進行編碼查詢的城市,支援傳入城市名、adcode 和 citycode
            // city: "010"
            radius: 1000 //範圍,預設:500
          });
          // 根據經緯度 擷取目前點選位置的城市code 用于周邊搜尋
          geocoder.getAddress(
            //根據目前的經緯度查找
            [this.userInfo.jd, this.userInfo.wd],
            (status, result) => {
              if (status === "complete" && result.info === "OK") {
                // result為對應的地理位置詳細資訊
                if (this.nearbyMarker && this.nearbyMarker.length > 0) {
                  this.nearbyMarker.forEach(element => {
                    // 每次切換學生的時候清空周邊所有 醫院和警察局錨點
                    element.setMap(null);
                  });
                }
                MSearch = new AMap.PlaceSearch({
                  pageSize: 20, // 單頁顯示結果條數
                  //構造地點查詢類
                  city: result.regeocode.addressComponent.citycode //城市
                });
                AMap.event.addListener(
                  MSearch,
                  "complete",
                  this.keywordSearch_CallBack
                ); //傳回地點查詢結果
                // 設定搜尋條件
                MSearch.searchNearBy(
                  // "綜合醫院|衛生院|公安警察",
                  this.nearbyType ,
                  // 設定搜尋中心店
                  [this.userInfo.jd, this.userInfo.wd],
                  // 設定中心店搜尋半徑
                  2000
                );
              }
            }
          );
        }
      );
    },
    //結果的回調
    keywordSearch_CallBack(data) {
      console.log(data);
      var poiArr = data.poiList.pois;
      var resultCount = poiArr.length;
      this.poiArr = poiArr; //左邊要渲染的資料
      // 周遊搜尋周邊資料
      poiArr.forEach((element, index) => {
        // 添加錨點
        this.addmarker(index, element);
      });
      console.log("第二處");
      this.aMap.setFitView();
    },
    //添加marker&infowindow
    addmarker(i, d) {
      var lngX = d.location.getLng();
      var latY = d.location.getLat();
      var markerOption = {
        map: this.aMap,
        position: new AMap.LngLat(lngX, latY), // 設定marker
        // 根據類型判斷顯示的圖檔
        icon:
          d.type.indexOf("政府機構及社會團體;") >= 0 ||
          d.type.indexOf("公安警察") >= 0 ||
          d.name.indexOf("警察") >= 0 ||
          d.name.indexOf("公安") >= 0
            ? this.police
            : this.hospital
      };
      // 設定marker坐标點
      var mar = new AMap.Marker(markerOption);
      // 記錄所有 選擇人後出現的醫院和警察局錨點
      // this.nearbyMarker.push(mar);
      // 資訊窗體設定
      var infoWindow = new AMap.InfoWindow({
        content:
          "<p class='nearby-item'>" +
          d.name +
          "</p>" +
          this.TipContents(d.name, d.address),
        //  + `</br><a  id="go"  href="javascript:;" target="_blank" rel="external nofollow" >立即前往</a>`,
        size: new AMap.Size(300, 0),
        autoMove: true,
        offset: new AMap.Pixel(0, -30)
      });
      // 彈出層界面處理
      // this.windowsArr.push(infoWindow);
      var _this = this;
      let winClick = e => {
        var obj = mar.getPosition();
        this.map = obj; //這裡儲存的位址經緯度
        this.address = d.name; //這裡儲存的是位址名字
        window.removeEventListener("click", _this.demo);
        infoWindow.open(_this.aMap, obj);
        window.addEventListener("click", _this.demo);
      };
      AMap.event.addListener(mar, "click", winClick);
    },
    TipContents(name, address) {
      //窗體内容
      if (
        name == "" ||
        name == "undefined" ||
        name == null ||
        name == " undefined" ||
        typeof name == "undefined"
      ) {
        type = "暫無";
      }
      if (
        address == "" ||
        address == "undefined" ||
        address == null ||
        address == " undefined" ||
        typeof address == "undefined"
      ) {
        address = "暫無";
      }
      var str = `位址:${address}`;
      return str;
    },
    demo(e) {
      if (e.target.id === `go`) {
        e.stopPropagation();
        this.saveAddress();
      }
    },
    saveAddress() {
      console.log("立即前往");
    },
    //軌迹繪制
    mapPolyline() {
      // 關閉高德資訊框
      this.aMap.clearInfoWindow();
     let path = [
    new AMap.LngLat(116.368904,39.913423),
    new AMap.LngLat(116.382122,39.901176),
    new AMap.LngLat(116.387271,39.912501),
    new AMap.LngLat( 116.397428,
        39.90923)
];
this.polyline = new AMap.Polyline({
    path: path,  
    borderWeight: 2, // 線條寬度,預設為 1
    strokeColor: 'red', // 線條顔色
    lineJoin: 'round' // 折線拐點連接配接處樣式
});
this.aMap.add(this.polyline);
    },
  }
};
</script>

<style  scoped>
#container {
  width: 100%;
  height: 100%;
  position: absolute;
  cursor: pointer;
}

/deep/ .marker-layout {
  width: 36px;
  height: 40px;

  background-repeat: no-repeat;
  background-size: 100%;
}
/deep/ .maker-layout-student {
  width: 25px;
  height: 25px;
  background-image: url("../assets/img/student.png");
}
/deep/ .amap-icon {
}
/deep/ .amap-icon img {
  width: 30px;
  height: 30px;
}
</style>