Uso básico del mapa Vue Gaode (@amap/amap-jsapi-loader): añadir marcadores, búsqueda de palabras clave de puntos de interés, planificación de rutas... (Método 1)

Prefacio: Introducir e inicializar el mapa de renderizado

Para conocer pasos específicos, consulte mi blog anterior, que explica en detalle cómo registrarse y solicitar la clave AutoNavi, la clave secreta, inicializar el mapa, etc.

vue-amap: vue-amap se basa en Vue 2.x y el componente de mapa de Gaode

Introducción oficial de AutoNavi: API JS de mapas

Introducción a la API de servicios web

La API de servicio web AutoNavi proporciona a los desarrolladores interfaces HTTP a través de las cuales pueden utilizar varios tipos de servicios de datos geográficos, y los resultados devueltos admiten formatos JSON y XML. La API del servicio web está abierta a todos los usuarios. Antes de utilizar este grupo de servicios, debe solicitar una clave de aplicación. Diferentes tipos de usuarios pueden obtener diferentes capacidades de acceso a datos.

1. Inicializar el mapa

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. Mapear el evento de clic del mouse

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

3. Agregar marca, eliminar punto de marca

inserte la descripción de la imagen aquí

//  添加标记
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. Servicio de búsqueda: búsqueda de palabras clave de puntos de interés [AMap.PlaceSearch]

inserte la descripción de la imagen aquí

Agregar complemento:

 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. Servicio de planificación de rutas de conducción.

inserte la descripción de la imagen aquí

5.1 Planificación de rutas de conducción mediante arrastrar y soltar [AMap.DragRoute]

Agregar complemento:

  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 Planificación de ruta para puntos de paso (punto de inicio, punto final, punto de paso) [AMap.Driving]

Agregar complemento:

  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 Posición, latitud y longitud + obtener datos de planificación de conducción [AMap.Driving]

  1. Prepare un contenedor div de panel, coloque datos de navegación y vincule una ID única
 <div id="panel"></div>
  1. Construir clase de navegación de ruta, planificar ruta de navegación de conducción de acuerdo con la latitud y longitud de los puntos de inicio y finalización

inserte la descripción de la imagen aquí

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 Resultados de la planificación + dibujo de ruta de conducción [AMap.Driving]

Agregar complemento:

 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);
    }
  });
},

Código completo:

<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>

Supongo que te gusta

Origin blog.csdn.net/qq_37831545/article/details/127048641
Recomendado
Clasificación