Vue 高德地图(@amap/amap-jsapi-loader)的基本使用:添加标记、POI关键字搜索、路线规划...(方法一)

前言: 引入并初始化渲染地图

具体的步骤可以参考我的上一篇博客,有详细说明如何注册申请高德的Key、秘钥,初始化地图等等

vue-amap : vue-amap 基于 Vue 2.x 与高德的地图组件

高德官方介绍:地图 JS API

Web服务API简介

高德Web服务API向开发者提供HTTP接口,开发者可通过这些接口使用各类型的地理数据服务,返回结果支持JSON和XML格式。Web服务API对所有用户开放。使用本组服务之前,需要申请应用Key。不同类型用户可获取不同的数据访问能力。

1、初始化地图

npm i @amap/amap-jsapi-loader --save
 <el-input v-model="location" id="tipinput"></el-input>
 <div id="map-container"></div>

 data() {
    
    
    return {
    
    
      location: "", // input的内容
      map: null,// 
      lnglat: [], // 经纬度数组 [lng,lat] 
      auto: null,
      placeSearch: null,
      markers: [],
      driving: null,
    };
  },
initMap() {
    
    
  AMapLoader.load({
    
    
    key: "XXXXXX", // 申请好的Web端开发者Key,首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
    plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Driving", "AMap.DragRoute"],
  })
    .then((AMap) => {
    
    
      this.map = new AMap.Map("map-container", {
    
    
        // 设置地图容器id
        viewMode: "2D", //  是否为3D地图模式
        zoom: 13, // 初始化地图级别
        center: [114.268691, 30.401227], //中心点坐标
        resizeEnable: true,
      });=
      // 监听鼠标点击事件
      this.map.on("click", this.clickMapHandler);
      // 函数调用(写入你先所需要的事件函数)
      // this.searchMap(); // POI关键字搜索
      // ...其他
    })
    .catch((e) => {
    
    
      console.log(e);
   });
}

2、地图鼠标点击事件

// 监听地图点击事件
 this.map.on("click", this.clickMapHandler);
// 点击地图事件获取经纬度,并添加标记
clickMapHandler(e) {
    
    
   this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
   this.setMarker(this.lnglat);
},

3、添加标记、 移除标记点

在这里插入图片描述

//  添加标记
setMarker(lnglat) {
    
    
  console.log("位置", lnglat); // lnglat=[经度,纬度]
  let marker = new AMap.Marker({
    
    
    position: lnglat,
  });
  marker.setMap(this.map);
  this.markers.push(marker); // 在data中记录标记点
},
// 删除之前后的标记点
removeMarker() {
    
    
// 判断是否存被标记的点,有--->移除
  if (this.markers) {
    
    
    this.map.remove(this.markers);
  }
},

4、搜索服务——POI关键字搜索 [AMap.PlaceSearch]

在这里插入图片描述

添加插件:

 plugins: [... ,  "AMap.PlaceSearch"],
// 地图关键字查询
searchMap() {
    
    
  // 搜索框自动完成类
  this.auto = new AMap.AutoComplete({
    
    
    input: "tipinput",
  });
  //构造地点查询类
  this.placeSearch = new AMap.PlaceSearch({
    
    
    map: this.map,
  });
  // 当选中某条搜索记录时触发
  this.auto.on("select", this.selectSite);
},

//当选中某条搜索记录时触发
selectSite(e) {
    
    
  this.lnglat = [e.poi.location.lng, e.poi.location.lat];
  this.placeSearch.setCity(e.poi.adcode);
  this.placeSearch.search(e.poi.name); 
},

5、驾车路线规划服务

在这里插入图片描述

5.1 可拖拽驾车路线规划 [AMap.DragRoute]

添加插件:

  plugins: [... , "AMap.DragRoute"],
// 绘制初始路径
 mapDragRoute() {
    
    
   var path = [];
   path.push([114.332138, 30.53802]);
   path.push([114.317433, 30.55351]);
   path.push([114.308783, 30.560878]);
   mapDragRoute;
   var route = new AMap.DragRoute(this.map, path, AMap.DrivingPolicy.LEAST_FEE); //构造拖拽导航类
   route.search(); //查询导航路径并开启拖拽导航
 },

5.2 途经点 (起点 终点 途经点 )路线规划 [AMap.Driving]

添加插件:

  plugins: [... , "AMap.Driving"],
drivingMap() {
    
    
  var driving = new AMap.Driving({
    
    
    map: map,
    panel: "panel",
  });
  // 根据起终点经纬度规划驾车导航路线
  driving.search(
    new AMap.LngLat(114.332138, 30.53802),
    new AMap.LngLat(114.308783, 30.560878),
    {
    
    
      waypoints: [new AMap.LngLat(114.317433, 30.55351)],
    },
    function (status, result) {
    
    
      // result 即是对应的驾车导航信息,相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
      if (status === "complete") {
    
    
        log.success("绘制驾车路线完成");
      } else {
    
    
        log.error("获取驾车数据失败:" + result);
      }
    });

5.3 位置经纬度 + 获取驾车规划数据 [AMap.Driving]

  1. 准备一个panel div容器,放置导航数据,绑定一个唯一的ID
 <div id="panel"></div>
  1. 构造路线导航类,据起终点经纬度规划驾车导航路线

在这里插入图片描述

drivingMapPanle() {
    
    
  //  配置参数
  var drivingOption = {
    
    
    policy: AMap.DrivingPolicy.LEAST_TIME, // 其它policy参数请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingPolicy
    ferry: 1, // 是否可以使用轮渡
    // province: "鄂", // 车牌省份的汉字缩写
    map: this.map,
    panel: "panel", // 绑定容器 id
  };
  // 构造路线导航类
  var driving = new AMap.Driving(drivingOption);
  // 根据起终点经纬度规划驾车导航路线
  ver start = new AMap.LngLat(116.379028, 39.865042)
  var end = new AMap.LngLat(116.427281, 39.903719)
  driving.search(start , end , function (status, result) {
    
    
    if (status === "complete") {
    
    
      console.log("绘制驾车路线完成");
    } else {
    
    
      console.log("获取驾车数据失败:" + result);
    }
  });
},

5.4 规划结果 + 驾车路线绘制 [AMap.Driving]

添加插件:

 plugins: [... , "AMap.Driving"],
drivingMap2() {
    
    
  let that = this;
  var driving = new AMap.Driving({
    
    
    // 驾车路线规划策略,AMap.DrivingPolicy.LEAST_TIME是最快捷模式,还有其他几种方式见Api文档
    policy: AMap.DrivingPolicy.LEAST_TIME,
  });
  //起、终点
  var start_xy = new AMap.LngLat(116.379028, 39.865042); // 起点的经纬度
  var end_xy = new AMap.LngLat(116.427281, 39.903719); // 终点的经纬度
  // 根据起终点经纬度规划驾车导航路线
  driving.search(start_xy, end_xy, function (status, result) {
    
    
    console.log(start_xy, end_xy, status, result);
    if (status === "complete") {
    
    
      if (result.routes && result.routes.length) {
    
    
        console.log(result.routes[0]);
         // 绘制第一条路线,也可以按需求绘制其它几条路线
        var path = that.parseRouteToPath(result.routes[0]);
        var startMarker = new AMap.Marker({
    
    
          position: path[0],
          icon: "https://webapi.amap.com/theme/v1.3/markers/n/start.png",
          map: that.map,
        });
        var endMarker = new AMap.Marker({
    
    
          position: path[path.length - 1],
          icon: "https://webapi.amap.com/theme/v1.3/markers/n/end.png",
          map: that.map,
        });
        var routeLine = new AMap.Polyline({
    
    
          path: path,
          isOutline: true,
          outlineColor: "#ffeeee",
          borderWeight: 2,
          strokeWeight: 5,
          strokeColor: "#0091ff",
          lineJoin: "round",
        });
        routeLine.setMap(that.map);
        // 调整视野达到最佳显示区域
        that.map.setFitView([startMarker, endMarker, routeLine]);
        console.log("绘制驾车路线完成");
      }
    } else {
    
    
      console.log("获取驾车数据失败:" + result);
    }
  });
},

完整代码:

<template>
  <div class="content">
    <div class="search-box">
      <div class="label">关键字搜索</div>
      <el-input v-model="input" placeholder="请输入内容" id="tipinput"></el-input>
    </div>
    <div id="map-container"></div>
    <div id="panel"></div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
window._AMapSecurityConfig = {
    
    
  // 设置安全密钥
  securityJsCode: "XXXXX",
};

export default {
    
    
  props: {
    
    
    iptId: {
    
    
      type: String,
    },
  },
  data() {
    
    
    return {
    
    
      input: "",
      map: null,
      lnglat: [], // [lng,lat]  [longitude,latitude]
      auto: null,
      placeSearch: null,
      markers: [],
      driving: null,
        };
  },
  mounted() {
    
    
    this.initMap();
  },
  created() {
    
    
    this.initMap();
  },
  methods: {
    
    
    initMap() {
    
    
      AMapLoader.load({
    
    
        key: "99d901020b4dcf6b08aa3bcdb4ab386d", // 申请好的Web端开发者Key,首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
        plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Driving", "AMap.DragRoute"],
      })
        .then((AMap) => {
    
    
          console.log(AMap);
          this.map = new AMap.Map("map-container", {
    
    
            // 设置地图容器id
            viewMode: "2D", //  是否为3D地图模式
            zoom: 13, // 初始化地图级别
             center: [114.268691, 30.401227], //中心点坐标
            resizeEnable: true,
          });
          //规划结果 + 驾车路线绘制
          //   this.drivingMap();
          //  可拖拽驾车路线规划 绘制初始路径
          //   this.mapDragRoute();
          this.drivingMapPanle();
          // 关键字查询
          this.searchMap();
          // 监听鼠标点击事件
          this.map.on("click", this.clickMapHandler);
        })
        .catch((e) => {
    
    
          console.log(e);
        });
    },
    // 绘制初始路径
    mapDragRoute() {
    
    
      var path = [];
      path.push([114.332138, 30.53802]);
      path.push([114.317433, 30.55351]);
      path.push([114.308783, 30.560878]);

      var route = new AMap.DragRoute(this.map, path, AMap.DrivingPolicy.LEAST_FEE); //构造拖拽导航类
      route.search(); //查询导航路径并开启拖拽导航
    },
    drivingMap() {
    
    
      var driving = new AMap.Driving({
    
    
        map: this.map,
        // panel: "panel",
      });
      // 根据起终点经纬度规划驾车导航路线
      driving.search(
        new AMap.LngLat(114.332138, 30.53802),
        new AMap.LngLat(114.308783, 30.560878),
        {
    
    
          waypoints: [new AMap.LngLat(114.317433, 30.55351)],
        },
        function (status, result) {
    
    
          // result 即是对应的驾车导航信息,相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
         if (status === "complete") {
    
    
            console.log("绘制驾车路线完成");
          } else {
    
    
            console.log("获取驾车数据失败:" + result);
          }
        });
     },
    drivingMapPanle() {
    
    
      // 配置参数
      var drivingOption = {
    
    
        policy: AMap.DrivingPolicy.LEAST_TIME, // 其它policy参数请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingPolicy
        ferry: 1, // 是否可以使用轮渡
        // province: "京", // 车牌省份的汉字缩写
        map: this.map,
        panel: "panel",
      };
      // 构造路线导航类
      var driving = new AMap.Driving(drivingOption);
      // 根据起终点经纬度规划驾车导航路线
      driving.search(new AMap.LngLat(116.379028, 39.865042), new AMap.LngLat(116.427281, 39.903719), function (status, result) {
    
    
         if (status === "complete") {
    
    
          log.success("绘制驾车路线完成");
        } else {
    
    
          log.error("获取驾车数据失败:" + result);
        }
      });
    },
    // 点击地图事件
    clickMapHandler(e) {
    
    
      this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
      this.setMarker(this.lnglat);
    },
    // 关键字查询
    searchMap() {
    
    
      // 搜索框自动完成类
      this.auto = new AMap.AutoComplete({
    
    
        input: "tipinput", // 使用联想输入的input的id
      });
      //构造地点查询类
      this.placeSearch = new AMap.PlaceSearch({
    
    
        map: this.map,
      });
      // 当选中某条搜索记录时触发
      this.auto.on("select", this.selectSite);
    },
    //当选中某条搜索记录时触发
    selectSite(e) {
    
    
      console.log("e", e);
      this.lnglat = [e.poi.location.lng, e.poi.location.lat];
      this.placeSearch.setCity(e.poi.adcode);
      this.placeSearch.search(e.poi.name); //关键字查询
    },
     //  添加标记
    setMarker(lnglat) {
    
    
      this.removeMarker();
      console.log("位置", lnglat);
      let marker = new AMap.Marker({
    
    
        position: lnglat,
      });
      marker.setMap(this.map);
      this.markers.push(marker);
    },
    // 删除之前后的标记点
    removeMarker() {
    
    
      if (this.markers) {
    
    
        this.map.remove(this.markers);
      }
    },
 },
};
</script>

<style lang="less" scoped>
.search-box {
    
    
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 50px;
  .label {
    
    
    width: 100px;
  }
}
.content {
    
    
  position: relative;
}
#panel {
    
    
  position: absolute;
  top: 50px;
  right: 20px;
}
#map-container {
    
    
  overflow: hidden;
  width: 100%;
  height: 800px;
  margin: 0;
}
</style>

猜你喜欢

转载自blog.csdn.net/qq_37831545/article/details/127048641
今日推荐