天天看点

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>