Vue 使用高德地图,添加点标记 + 点击地图获取坐标 + 带搜索(即地理编码 + 逆地理编码) - 附完整示例

高德地图

与真实世界联通 - 高德开放平台为开发者赋能,将地图精致地呈现在您的应用中

无论基于哪种平台,都可以通过高德开放平台API和SDK,轻松地完成地图的构建工作

目录

 效果

一、介绍

1、官方文档:地图 | 高德地图API

二、准备工作

1、注册/登录账号

2、点击控制台

3、创建应用

4、获取key和密钥,如上图所示

三、安装依赖包

1、安装命令

 2、这是我的版本 

四、使用步骤

1、在index.html文件中引入密钥

2、在vue文件中引入依赖包

3、申明变量并初始化调用

五、完整示例

  欢迎扫描下方二维码关注VX公众号


 效果

一、介绍

1、官方文档:地图 | 高德地图API

地图 | 高德地图API地图,地图sdk,地图JS API,地图定制,自定义地图,地图覆盖物,地图绘制,路线规划,坐标转换,距离/面积计算,距离测量,室内地图,地图显示,地图个性化,地图开发,室内定位icon-default.png?t=N7T8https://lbs.amap.com/product/map#/

二、准备工作

1、注册/登录账号

2、点击控制台

3、创建应用

4、获取key和密钥,如上图所示

注:使用web服务API,如下图所示

三、安装依赖包

1、安装命令

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

 2、这是我的版本 

"@amap/amap-jsapi-loader": "^1.0.1",

四、使用步骤

1、在index.html文件中引入密钥

代码如下(示例):

<script type="text/javascript">
    window._AMapSecurityConfig = {
      securityJsCode: '', // 你的密钥
    }
  </script>

2、在vue文件中引入依赖包

代码如下(示例):

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

3、申明变量并初始化调用

代码如下(示例):


import { shallowRef, defineEmits, ref, onBeforeUnmount } from 'vue';

const map = shallowRef(null);
let AMapObj, placeSearch, marker, geocoder;

function initMap(){
  AMapLoader.load({
    key:'',  //设置您的key
    version:"2.0",
    plugins:['AMap.ToolBar','AMap.Driving'],
    AMapUI:{
      version:"1.1",
      plugins:[],

    },
    Loca:{
      version:"2.0.0"
    },
  }).then((AMap)=>{
    // console.log(AMap);
    AMapObj = AMap;
    map.value = new AMap.Map("map-box",{
      viewMode:"3D",
      zoom:10,
      zooms:[2,22],
      center: [105.602725,37.076636],
    });
    map.value.on('click', onMapClick);
    AMap.plugin(
      ['AMap.ToolBar','AMap.Scale','AMap.Geolocation','AMap.PlaceSearch',
        'AMap.Geocoder','AMap.AutoComplete'],
      () => {
        // 缩放条
        const toolbar = new AMap.ToolBar();
        // 比例尺
        const scale = new AMap.Scale();
        // 定位
        const geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, //是否使用高精度定位,默认:true
          timeout: 10000, //超过10秒后停止定位,默认:5s
          position: 'RT', //定位按钮的停靠位置
          buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
          zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
        });
        geocoder = new AMap.Geocoder({
          city: '全国',
        });
        map.value.addControl(geolocation);
        map.value.addControl(toolbar);
        map.value.addControl(scale);
        placeSearch = new AMap.PlaceSearch({
          // map: map.value,
          city: '全国',
          pageSize: 10, // 单页显示结果条数
          pageIndex: 1, // 页码
          citylimit: false, // 是否强制限制在设置的城市内搜索
          autoFitView: true,
        });
      });
  }).catch(e=>{
    console.log(e);
  })
}

initMap();

五、完整示例

Index.html

<!DOCTYPE html>
<html lang="zh_CN" id="htmlRoot">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  <meta name="renderer" content="webkit" />
  <meta name="viewport"
    content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=0" />

  <title>
    <%= title %>
  </title>
  <script type="text/javascript">
    window._AMapSecurityConfig = {
      securityJsCode: '', // 你的密钥
    }
  </script>
  
</head>

<body>
  <div id="app">
  </div>
</body>

</html>

Map.vue

<template>
  <div class="home">
    <div id="map-box"></div>
    <div class="info-box">
      <a-select
        v-model:value="keyword"
        show-search
        placeholder="输入关键字搜索"
        style="width: 300px"
        :default-active-first-option="false"
        :show-arrow="false"
        :filter-option="false"
        :not-found-content="null"
        @search="handleSearch"
      >
        <a-select-option v-for="item in data" :key="item.id" :value="item.id" @click="handleSelect(item)">
          <div class="d-flex flex-column">
            <span>{{item.name}}</span>
            <span style="font-size: '10px'; color: #999999">{{item.address}}</span>
          </div>
        </a-select-option>
      </a-select>
      <a-tooltip>
        <template #title v-if="coord">点击复制</template>
        <span style="margin: 5px 8px;">
          经纬度:<span class="copy" style="cursor: pointer;" :data-clipboard-text="coord">{{coord}}</span>
        </span>
      </a-tooltip>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { shallowRef, ref, onBeforeUnmount } from 'vue';
import AMapLoader from "@amap/amap-jsapi-loader";
import { message } from 'ant-design-vue';
import ClipboardJS from 'clipboard';
   
const clipboard = new ClipboardJS('.copy');

clipboard.on('success', function(e) {
  console.log(e);
  console.info('Text:', e.text);
  message.info('复制成功');
  e.clearSelection();
});

clipboard.on('error', function(e) {
  if(!e.text) message.error('暂无可复制的内容')
});

onBeforeUnmount(() => {
  clipboard.destroy();
})

const map = shallowRef(null);
const keyword = ref(null);
const data = ref([]);
const coord = ref('');
let AMapObj, placeSearch, marker, geocoder;

function initMap(){
  AMapLoader.load({
    key: '',  //设置您的key
    version: "2.0",
    plugins: ['AMap.ToolBar','AMap.Driving'],
    AMapUI: {
      version: "1.1",
      plugins: [],

    },
    Loca:{
      version: "2.0.0"
    },
  }).then((AMap)=>{
    // console.log(AMap);
    AMapObj = AMap;
    map.value = new AMap.Map("map-box",{
      viewMode:"3D",
      zoom:10,
      zooms:[2,22],
      center: [105.602725,37.076636],
    });
    map.value.on('click', onMapClick);
    AMap.plugin(
      ['AMap.ToolBar','AMap.Scale','AMap.Geolocation','AMap.PlaceSearch',
        'AMap.Geocoder','AMap.AutoComplete'],
      () => {
        // 缩放条
        const toolbar = new AMap.ToolBar();
        // 比例尺
        const scale = new AMap.Scale();
        // 定位
        const geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, // 是否使用高精度定位,默认:true
          timeout: 10000, // 超过10秒后停止定位,默认:5s
          position: 'RT', // 定位按钮的停靠位置
          buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
          zoomToAccuracy: true, // 定位成功后是否自动调整地图视野到定位点
        });
        geocoder = new AMap.Geocoder({
          city: '全国',
        });
        map.value.addControl(geolocation);
        map.value.addControl(toolbar);
        map.value.addControl(scale);
        placeSearch = new AMap.PlaceSearch({
          city: '全国',
          pageSize: 10, // 单页显示结果条数
          pageIndex: 1, // 页码
          citylimit: false, // 是否强制限制在设置的城市内搜索
          autoFitView: true,
        });
      });
  }).catch(e=>{
    console.log(e);
  })
}

// 搜索地图
function handleSearch(str) {
  placeSearch.search(str, (status, result) => {
    console.log(result);
    if (result && typeof result === 'object' && result.poiList) {
      const list = result.poiList.pois;
      list.forEach(item => {
        item.value = item.name;
        item.label = item.name;
      });
      data.value = list
    }
  });
}
// 点击地图
function onMapClick(e) {
  coord.value = e.lnglat.lng + ',' + e.lnglat.lat
  geocoder.getAddress([e.lnglat.lng, e.lnglat.lat], function(status, result) {
    if (status === 'complete' && result.info === 'OK') {
      // result为对应的地理位置详细信息
      keyword.value = result.regeocode.formattedAddress
    }
  })
  drawMarker(e.lnglat)
}
// 点击搜索项
function handleSelect(item) {
  console.log(item);
  drawMarker(item.location)
  if (item.location != null) {
    coord.value = item.location.lng + ',' + item.location.lat
  }
}
// 绘制地点marker
function drawMarker(location) {
  if (location == null) return
  let longitude = location.lng, latitude = location.lat
  if (marker) {
    marker.setMap(null);
  }
  marker = new AMapObj.Marker({
    position: new AMapObj.LngLat(longitude, latitude),
    anchor: 'bottom-center',
  });
  marker.on('click', () => {
    coord.value = location;
  })
  map.value.add(marker);
  map.value.setZoomAndCenter(16, [longitude, latitude]);
}

initMap();

</script>

<style lang="less" scoped>
.home{
  height: 500px;
  width: 100%;
  padding: 0px;
  margin: 0px;
  position: relative;

  .info-box {
    position: absolute;
    top: 8px;
    right: 8px;
    width: 300px;
    background-color: #1f1f1f;
    display: flex;
    flex-direction: column;
  }
}
#map-box{
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}
</style>

<style scoped>
:deep() .amap-logo {
  display: none !important;
}
:deep() .amap-copyright {
  display: none !important;
}
</style>

注:clipboard一键复制的详细使用方法参考地址

https://mp.csdn.net/mp_blog/creation/editor/131308740

  欢迎扫描下方二维码关注VX公众号

  • 2
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Vue 高德地图地理编码可以使用 AMap JavaScript API 实现。以下是一个简单的示例: 首先需要在 `index.html` 中引入高德地图 JavaScript API: ```html <script src="https://webapi.amap.com/maps?v=1.4.15&key=your-amap-key"></script> ``` 然后在 Vue 组件中,可以使用以下代码获取当前位置的地理编码信息: ```vue <template> <div> <div ref="map" style="width: 100%; height: 400px;"></div> <div>{{ address }}</div> </div> </template> <script> export default { data() { return { address: "" }; }, mounted() { // 创建地图 const map = new AMap.Map(this.$refs.map, { zoom: 16 }); // 获取当前位置 map.plugin("AMap.Geolocation", () => { const geolocation = new AMap.Geolocation({ enableHighAccuracy: true, // 是否使用高精度定位,默认为 false timeout: 10000, // 超过 10 秒后停止定位,默认值为 无穷大 maximumAge: 0, // 定位结果缓存时间,默认值为 0 convert: true, // 自动偏移坐标,偏移后的坐标为高德坐标,默认为 true showButton: true, // 显示定位按钮,默认为 true buttonPosition: "LB", // 定位按钮的位置,默认为 'LB',左下角 buttonOffset: new AMap.Pixel(10, 10), // 定位按钮距离容器左下角的偏移量,默认为 Pixel(10, 20) showMarker: true, // 定位成功后在定位到的位置显示标记,默认为 true showCircle: true, // 定位成功后用圆圈表示定位精度范围,默认为 true panToLocation: true, // 定位成功后将定位到的位置作为地图中心,默认为 true zoomToAccuracy: true // 定位成功后自动调整地图缩放级别以适合定位结果的范围,默认为 true }); geolocation.getCurrentPosition((status, result) => { if (status === "complete") { this.getAddress(result.address); } else { console.log("获取当前位置信息失败"); } }); }); }, methods: { // 地理编码 getAddress(address) { this.address = address; } } }; </script> ``` 在 `mounted` 钩子函数中,我们使用 `AMap.Geolocation` 插件获取当前位置信息。然后在 `getCurrentPosition` 回调函数中,我们通过 `result.address` 获取当前位置的地理编码信息,并将其赋值给 `this.address`,以在页面中显示。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值