❤ Vue使用高德地图

❤ 高德地图的使用

1、简介

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

https://console.amap.com/
在这里插入图片描述

注册自己的高德地图key

2、script在线引入使用 (非正规使用)

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

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

2.0版本的引入和使用
<script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key="></script>

使用

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>AMap JSAPI Loader</title>
    <style>
        html, body, #container {
            height: 100%;
            width: 100%;
            margin: 0;
        }
    </style>
  <script src="https://webapi.amap.com/loader.js"></script>
</head>
<body>
<div id="container" tabindex="0"></div>
<script>
    var map;
    AMapLoader.load({ //首次调用 load
        key:'',//首次load key为必填
        version:'2.0',
        plugins:['AMap.Scale','AMap.ToolBar']
    }).then((AMap)=>{
        map = new AMap.Map('container');
        map.addControl(new AMap.Scale())
        map.addControl(new AMap.ToolBar())
        map.add(new AMap.Marker({
            position:map.getCenter()
        }));
    }).catch((e)=>{
        console.error(e);
    });
   
    AMapLoader.load({ //可多次调用load
        plugins:['AMap.MapType']
    }).then((AMap)=>{
        map.addControl(new AMap.MapType())
    }).catch((e)=>{
        console.error(e);
    });
   
</script>
</body>
</html>

3、JS API 结合 Vue 使用 (正规使用)

(1)安装地图插件

按 NPM 方式安装使用 Loader

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

(2)引入 JS API Loader

  import AMapLoader from "@amap/amap-jsapi-loader";

(3)JS API Loader 进行加载

结构
<div id="container"></div>

css
#container {
  width: 100%;
  height: 400px;
}


script

 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], // 初始化地图中心点位置
            });
          })
          .catch((e) => {
            console.log(e);
     });
 },

(4)地图销毁

销毁地图官方提示是this.map?.destroy(),这里建议采用v-if和v-show

unmounted() {
    //   this.map?.destroy();
    this.showmap=false;
  },

(5)添加标记点

插件之中要记得添加:
plugins: ['AMap.Driving','AMap.Marker'],


 // 添加地图点
addMarker(){ 
      let _this = this;
     _this.marker = new AMap.Marker({
         position: new AMap.LngLat(_this.center[0], _this.center[1], ), // 经纬度对象,也可以是经纬度构成的一维数组[116.39, 39.9]
         title: '地点',
         icon: 'http://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',//图标
       });
       // 将创建的点标记添加到已有的地图实例:
       _this.map.add(_this.marker);
   },

(6)添加实时路况图层


 addMaptuceng() {
    //实时路况图层
  	var trafficLayer = new AMap.TileLayer.Traffic({
         zIndex: 10
    });
    map.add(trafficLayer);//添加图层到地图
 },

4、插件一揽

在这里插入图片描述

二、高德地图插件(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>
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue使用高德地图可以通过以下步骤进行: 1. 注册并登录高德地图开放平台,申请密钥。 2. 安装高德地图加载器,可以使用命令`npm install vue-amap --save`进行安装。 3. 在Vue组件中引入vue-amap模块。 4. 封装一个自定义地图组件,并在组件中初始化地图。 5. 可以使用高德地图提供的API进行关键词搜索和定位到搜索结果的位置。 6. 添加放大缩小地图、转盘等功能可以使用高德地图的控件或API进行实现。 7. 可以通过点击地图获取经纬度信息。 8. 地图上可以绘制标记点、圆形、曲线、矩形和多边形等。 9. 可以使用相关方法清除地图上的绘制内容。 总结起来,在Vue使用高德地图,首先需要安装相关依赖并注册密钥,然后引入模块并在组件中初始化地图,最后可以根据需求使用高德地图的API实现各种功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [在Vue使用高德地图](https://blog.csdn.net/weixin_44224921/article/details/126105778)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [Vue使用高德地图](https://blog.csdn.net/TanHao8/article/details/117048193)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林太白

感谢打赏,你拥有了我VIP权限

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值