❤ Vue中使用高德地图

❤ 一、Vue中使用高德地图(script 引入方式实现在线加载)

1、认识

官网找到对应的web服务文档

在这里插入图片描述

2、使用

🌂 1、注册自己的高德地图key

2、页面上引入使用自己的高德地图key

安装地图插件

按 NPM 方式安装使用 Loader

npm i @amap/amap-jsapi-loader --save

2.0版本的引入和使用

在线引用

<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=您申请的key值"></script>

<script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key="></script>
引入 JS API Loader
  import AMapLoader from "@amap/amap-jsapi-loader";

JS API Loader 进行加载

 window._AMapSecurityConfig = {
    securityJsCode: "「你申请的安全密钥」",
 };

 mounted() {
      this.initAMap();
 },

 initAMap() {
        AMapLoader.load({
          key: "", // 申请好的Web端开发者Key,首次调用 load 时必填
          version: "2.0", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
          plugins: [], // 需要使用的的插件列表,如比例尺'AMap.Scale'})
          .then((AMap) => {
            this.map = new AMap.Map("container", {
              // 设置地图容器id
              viewMode: "3D", // 是否为3D地图模式
              zoom: 13, // 初始化地图级别
              center: [116.397428, 39.90923], // 初始化地图中心点位置
            });

            // 创建点覆盖物
            var marker = new AMap.Marker({
                position: new AMap.LngLat(116.397428, 39.90923),
                icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
                offset: new AMap.Pixel(-13, -30)
            });
            this.map.add(marker);
          })
          .catch((e) => {
            console.log(e);
          });
      },

🌂 3、页面上使用自己的高德地图

1、写入容器

 <div id="gaomap" class="gaomap" style="width: 100%;height: 80vh"></div>
 
2、mounted里面写上方法
 this.initMap();
3、methods里面写上方法
 initMap() {
      var map = new AMap.Map('containers', {
                zoom: 13,//级别 3-17  越大显示越细节
                center: [116.397428, 39.90923],//中心点坐标
                viewMode: '3D'//使用3D视图
           });
        //实时路况图层
      	var trafficLayer = new AMap.TileLayer.Traffic({
             zIndex: 10
        });
        map.add(trafficLayer);//添加图层到地图

 },

3、进一步使用

(1) 渲染地图
 initMap() {
      let _this = this;
      AMapLoader.load({ //可多次调用load
        key: "自己申请的key",
        plugins: ['AMap.Marker']
      }).then((AMap) => {
        _this.map = new AMap.Map("gaomap", { //设置地图容器id
          zoom: 13, //初始化地图级别
          center: _this.center, //地图中心点
        });
      }).catch((e) => {
        console.error(e);
      });
    },
(2) 添加标记

❤ 高德地图(JSAPI)的使用-JSAPI结合Vue

1、按 NPM 方式安装使用 Loader

yarn add @amap/amap-jsapi-loader --save

2、正常使用

<script setup>
import { onMounted, onUnmounted } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";

let map = null;

onMounted(() => {
  AMapLoader.load({
    key: "", // 申请好的Web端开发者Key,首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
    plugins: [], // 需要使用的的插件列表,如比例尺'AMap.Scale'})
    .then((AMap) => {
      map = new AMap.Map("container", {
        // 设置地图容器id
        viewMode: "3D", // 是否为3D地图模式
        zoom: 11, // 初始化地图级别
        center: [116.397428, 39.90923], // 初始化地图中心点位置
      });
    })
    .catch((e) => {
      console.log(e);
    });
});

onUnmounted(() => {
  map?.destroy();
});
</script>

<template>
  <div id="container"></div>
</template>

<style scoped>
#container {
  width: 100%;
  height: 800px;
}
</style>

二、高德地图插件(vue-amap)的使用

实现地图的点击地址和经纬度的转换并显示

❤ vue-amap安装和使用

  • 基于 Vue 2.0 和高德地图
  • ElementUI

❤ 1.npm 安装

npm install vue-amap --save

CDN方式

<script src="https://unpkg.com/vue-amap/dist/index.js"></script>

❤ 2、main.js引入

○ 安装后在main.js中设置以下内容

import VueAMap from "vue-amap"; //导入
Vue.use(VueAMap); //使用
// 初始化vue-amap
VueAMap.initAMapApiLoader({
  key: "your key", // 你申请的高德地图的key 
  plugin: ["AMap.Autocomplete", "AMap.Geocoder", "AMap.Geolocation"],
  v: "1.4.15",
  uiVersion: "1.1"
});

❤3、写成组件mapps.vue

<template>
  <div>
    <div class="search-box">
      <el-input 
        style="margin-bottom: 20px;"
        v-model="searchKey"
        type="search"
        id="search"
        placeholder="请输入详细地址"
      ></el-input>
      <!--<button @click="searchByHand">搜索</button>-->
      <div class="tip-box" id="searchTip"></div>
    </div>
    <!--
      amap-manager: 地图管理对象
      vid:地图容器节点的ID
      zooms: 地图显示的缩放级别范围,在PC上,默认范围[3,18],取值范围[3-18];在移动设备上,默认范围[3-19],取值范围[3-19]
      center: 地图中心点坐标值
      plugin:地图使用的插件
      events: 事件
    -->
    <div style="margin-bottom: 20px;">
      <span>您选择的地址有:{{addresscon}}</span>
    </div>
    <div class="amap-box">
      <el-amap
        :amap-manager="amapManager"
        :vid="'amap-vue'"
        :zoom="zoom"
        :plugin="plugin"
        :center="center"
        :events="events"
      >
        <!-- 标记 -->
        <el-amap-marker
          v-for="(marker, index) in markers"
          :position="marker"
          :key="index"
        ></el-amap-marker>
      </el-amap>
    </div>
  </div>
</template>
<script>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=你的key&plugin=AMap.Geocoder"></script>
import { AMapManager, lazyAMapApiLoaderInstance } from "vue-amap";
let amapManager = new AMapManager();
export default {
  props: ["city", "value", "longitude", "latitude", "isEdit"],
  data() {
    let self = this;
    return {
      addresscon:'',
      address: null,
      searchKey: "",
      amapManager,
      markers: [],
      searchOption: {
        city: this.city ? this.city : "全国",
        citylimit: true
      },
      center: [121.329402, 31.228667],
      zoom: 13,
      lng: 0,
      lat: 0,
      loaded: false,
      events: {
        init() {
          lazyAMapApiLoaderInstance.load().then(() => {
            self.initSearch();
          });
        },
        // 点击获取地址的数据
        click(e) {
          // self.markers = [];
          let { lng, lat } = e.lnglat;
          self.lng = lng;
          self.lat = lat;
          self.center = [lng, lat];
          self.markers.push([lng, lat]);
          console.log(self.markers);
          // 这里通过高德 SDK 完成。
          let geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
          });
          geocoder.getAddress([lng, lat], function(status, result) {
            if (status === "complete" && result.info === "OK") {
              if (result && result.regeocode) {
                self.address = result.regeocode.formattedAddress;
                self.addresscon=self.addresscon+result.regeocode.formattedAddress+'、';
                console.log(result.regeocode.formattedAddress);
                // this.addresscon=this.addresscon+'、'+result.regeocode.formattedAddress+'';
                self.searchKey = result.regeocode.formattedAddress;
                self.$emit("updateLocation", lng, lat, self.searchKey);
                self.$nextTick();
              }

            }
          });
        }
      },
      // 一些工具插件
      plugin: [
        {
          // 定位
          pName: "Geolocation",
          events: {
            init(o) {
              // o是高德地图定位插件实例
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  if (self.isEdit) {
                    // 设置经度
                    self.lng = self.longitude;
                    // 设置维度
                    self.lat = self.latitude;
                    // 设置坐标
                    self.center = [self.longitude, self.latitude];
                    self.markers.push([self.longitude, self.latitude]);
                  } else {
                    // 设置经度
                    self.lng = result.position.lng;
                    // 设置维度
                    self.lat = result.position.lat;
                    // 设置坐标
                    self.center = [self.lng, self.lat];
                    self.markers.push([self.lng, self.lat]);
                  }
                  // load
                  self.loaded = true;
                  // 页面渲染好后
                  self.$nextTick();
                }
              });
            }
          }
        }
      ]
    };
  },
  created() {
    if (this.value) {
      this.searchKey = this.value;
      this.address = this.value;
    }
    if (this.longitude && this.latitude) {
      this.lng = this.longitude;
      this.lat = this.latitude;
      this.center = [this.longitude, this.latitude];
      this.markers.push([this.longitude, this.latitude]);
    }
  },
  methods: {
    // 选择地址后自动定位到当前地址附近
    updateAddress(value, longitude, latitude) {
      this.searchKey = value;
      this.address = value;
      this.lng = longitude;
      this.lat = latitude;
      this.center = [longitude, latitude];
      this.markers.push([longitude, latitude]);
    },
    initSearch() {
      let vm = this;
      let map = this.amapManager.getMap();
      AMapUI.loadUI(["misc/PoiPicker"], function(PoiPicker) {
        let poiPicker = new PoiPicker({
          input: "search",
          placeSearchOptions: {
            map: map,
            pageSize: 10
          },
          suggestContainer: "searchTip",
          searchResultsContainer: "searchTip"
        });
        vm.poiPicker = poiPicker;
        // 监听poi选中信息
        poiPicker.on("poiPicked", function(poiResult) {
          let source = poiResult.source;
          let poi = poiResult.item;
          if (source !== "search") {
            poiPicker.searchByKeyword(poi.name);
          } else {
            poiPicker.clearSearchResults();
            vm.markers = [];
            let lng = poi.location.lng;
            let lat = poi.location.lat;
            let address = poi.name; // poi.cityname + poi.adname + poi.name
            vm.center = [lng, lat];
            vm.markers.push([lng, lat]);
            vm.lng = lng;
            vm.lat = lat;
            vm.address = address;
            vm.searchKey = address;
            vm.$emit("updateLocation", lng, lat, vm.searchKey);
          }
        });
      });
    },
    searchByHand() {
      if (this.searchKey !== "" && this.poiPicker) {
        this.poiPicker.searchByKeyword(this.searchKey);
      }
    }
  }
};
</script>
<style>
	.search-box {
	  margin-top: 6px;
	  width: 100%;
	}
	.search-box input {
	  padding: 0 15px;
	  width: 100%;
	  height: 32px;
	  line-height: 32px;
	  color: #606266;
	  border: 1px solid #dcdfe6;
	  border-radius: 4px;
	}
	.search-box input:focus {
	  border-color: #409eff;
	  outline: 0;
	}
	.search-box input::-webkit-input-placeholder {
	  color: #c0c4cc;
	}
	.tip-box {
	  width: 100%;
	  max-height:280px;
	  position: absolute;
	  top: 72px;
	  z-index: 10000;
	  overflow-y: auto;
	  background-color: #fff;
	}

	.amap-ui-poi-picker-sugg,
	.amap_lib_placeSearch {
	  border: 1px solid #eee;
	  border-radius: 4px;
	}
	.amap-box {
	  height: 200px;
	}
</style>

❤4、使用组件

import mapps from '@/components/Mapgather/mapps.vue'  // 地图经纬度转换2
components: {mapps},

<mapps ref="mapps"></mapps>