vue对高德地图的使用和打点标记

该文章介绍了如何在Vue应用程序中集成高德地图API,包括注册账号创建应用、下载并初始化地图包、实现地图点击添加标记、进行地址逆解析以及设置搜索提示功能。代码示例详细展示了从地图加载到交互功能的实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一步:进入高德开放平台,跟着步骤注册账号,创建应用

创建时服务平台要选择【web端(JS API)】

第二步:用npm下载包,初始化地图

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

<template>
  <div id="container" class="container"></div>
</template>
 
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
window._AMapSecurityConfig = {
  // 安全密钥
  securityJsCode: "95869xxxxxxxxxxxxxxxxx53df87dfb",
};
export default {
  name: "TestIndex",
  methods: {
    initMap() {
      AMapLoader.load({
        // 你申请的Key
        key: "c31bea684xxxxxxxxxxxxxxxxxbbd92442",
        version: "2.0",
        // 需要用到的插件
        plugins: ["AMap.Geocoder", "AMap.AutoComplete"],
      })
        .then((AMap) => {})
        .catch((err) => {
          // 错误
          console.log(err);
        });
    },
  },
  mounted() {
    this.initMap();
  },
};
</script>
 
<style>
.container {
  width: 500px;
  height: 300px;
}
</style>

第三步:实现点击地图添加标记

<template>
  <div id="container" class="container"></div>
</template>
 
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
window._AMapSecurityConfig = {
  // 安全密钥
  securityJsCode: "95869abfxxxxxxxxxxxxxxxx53df87dfb",
};
export default {
  name: "TestIndex",
  data() {
    return {
      // 地图实例
      map: null,
      // 标记点
      marker: "",
      // 位置信息
      form: {
        lng: "",
        lat: "",
        address: "",
        //地区编码
        adcode: "",
      },
    };
  },
  methods: {
    initMap() {
      AMapLoader.load({
        // 你申请的Key
        key: "c31bea68xxxxxxxxxxxxxxxxd92442",
        version: "2.0",
        // 需要用到的插件
        plugins: ["AMap.Geocoder", "AMap.AutoComplete"],
      })
        .then((AMap) => {
          this.map = new AMap.Map("container", {
            viewMode: "3D", //是否为3D地图模式
            zoom: 5, //初始化地图级别
            center: [105.602725, 37.076636], //初始化地图中心点位置
          });
          //点击获取经纬度;
          this.map.on("click", (e) => {
            // 获取经纬度
            this.form.lng = e.lnglat.lng;
            this.form.lat = e.lnglat.lat;
            // 清除点
            this.removeMarker();
            // 标记点
            this.setMapMarker();
          });
        })
        .catch((err) => {
          // 错误
          console.log(err);
        });
    },
    // 标记点
    setMapMarker() {
      // 自动适应显示想显示的范围区域
      this.map.setFitView();
      this.marker = new AMap.Marker({
        map: this.map,
        position: [this.form.lng, this.form.lat],
      });
      this.map.setFitView();
      this.map.add(this.marker);
    },
    // 清除点
    removeMarker() {
      if (this.marker) {
        this.map.remove(this.marker);
      }
    },
  },
  mounted() {
    this.initMap();
  },
};
</script>
 
<style>
.container {
  width: 500px;
  height: 300px;
}
</style>
第四步:点击获取详细地址

在初始化地图的时候,实例化逆地理解析的插件:

 //地址逆解析;
          this.geoCoder = new AMap.Geocoder({
            city: "010", //城市设为北京,默认:“全国”
            radius: 1000, //范围,默认:500
          });

 在methods中直接定义一个函数:

// 逆解析地址
    toGeoCoder() {
      let lnglat = [this.form.lng, this.form.lat];
      this.geoCoder.getAddress(lnglat, (status, result) => {
        if (status === "complete" && result.regeocode) {
          this.form.address = result.regeocode.formattedAddress;
        }
      });
    },

第五步:搜索获取相关地区提示

全国需要换成搜索的城市例如'石家庄'

this.AutoComplete = new AMap.AutoComplete({ city: "全国" });

第六步:全部代码

<template>
  <div style="display: flex">
    <div>
      <div>
        <el-select
            v-model="keywords"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
            :loading="loading"
            :clearable="true"
            size="mini"
            @change="currentSelect"
            style="width: 500px"
        >
          <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item"
              class="one-text"
          >
            <span style="float: left">{{ item.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.district
              }}</span>
          </el-option>
        </el-select>
      </div>
      <div id="container" class="container"></div>
    </div>
    <div class="info-box">
      纬度:{{ form.lat }}
      <br />
      经度:{{ form.lng }}
      <p>详细地址:{{ form.address }}</p>
    </div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
window._AMapSecurityConfig = {
  // 安全密钥
  securityJsCode: "你申请的密钥",
};
export default {
  name: "TestIndex",
  data() {
    return {
      val:{
        location:{
          lat:'38.017837',
          lng:'114.44082',
        }
      },

      // 地图实例
      map: null,
      // 标记点
      marker: "",
      // 地址逆解析
      geoCoder: null,
      // 搜索提示
      AutoComplete: null,
      // 搜索关键字
      keywords: "",
      // 位置信息
      form: {
        lng: "",
        lat: "",
        address: "",
        adcode: "", //地区编码
      },
      // 搜索节流阀
      loading: false,
      // 搜索提示信息
      options: [],
    };
  },
  mounted() {
    this.initMap();
    this.currentSelect(this.val)
  },
  methods: {
    initMap() {
      AMapLoader.load({
        // 你申请的Key
        key: "你申请的Key",
        version: "2.0",
        // 需要用到的插件
        plugins: ["AMap.Geocoder", "AMap.AutoComplete"],
      })
          .then((AMap) => {
            this.map = new AMap.Map("container", {
              viewMode: "2D", //是否为3D地图模式
              zoom: 5, //初始化地图级别
              center: [105.602725, 37.076636], //初始化地图中心点位置
            });
            //地址逆解析插件
            this.geoCoder = new AMap.Geocoder({
              city: "010", //城市设为北京,默认:“全国”
              radius: 1000, //范围,默认:500
            });
            // 搜索提示插件
            this.AutoComplete = new AMap.AutoComplete({ city: "石家庄" });
            //点击获取经纬度;
            this.map.on("click", (e) => {
              // 获取经纬度
              this.form.lng = e.lnglat.lng;
              this.form.lat = e.lnglat.lat;
              // 清除点
              this.removeMarker();
              // 标记点
              this.setMapMarker(AMap);
            });
          })
          .catch((err) => {
            // 错误
            console.log(err);
          });
    },
    // 标记点
    setMapMarker(AMap) {
      console.log(AMap)
      // 自动适应显示想显示的范围区域
      this.map.setFitView();
      this.marker = new AMap.Marker({
        map: this.map,
        position: [this.form.lng, this.form.lat],
      });
      // 逆解析地址
      this.toGeoCoder();
      this.map.setFitView();
      this.map.add(this.marker);
    },
    // 清除点
    removeMarker() {
      if (this.marker) {
        this.map.remove(this.marker);
      }
    },
    // 逆解析地址
    toGeoCoder() {
      let lnglat = [this.form.lng, this.form.lat];
      this.geoCoder.getAddress(lnglat, (status, result) => {
        if (status === "complete" && result.regeocode) {
          this.form.address = result.regeocode.formattedAddress;
          this.keywords = result.regeocode.formattedAddress
        }
      });
    },
    // 搜索
    remoteMethod(query) {
      console.log(query);
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.AutoComplete.search(query, (status, result) => {
            this.options = result.tips;
            console.log(this.options)
          });
        }, 200);
      } else {
        this.options = [];
      }
    },
    // 选中提示
    currentSelect(val) {
      console.log(val)
      // 清空时不执行后面代码
      if (!val) {
        return;
      }
      this.keywords = val.name
      this.form = {
        lng: val.location.lng,
        lat: val.location.lat,
        // address: val.district + val.address,
        // adcode: val.adcode,
      };
      AMapLoader.load({
        // 你申请的Key
        key: "你申请的Key",
        version: "2.0",
        // 需要用到的插件
        plugins: ["AMap.Geocoder", "AMap.AutoComplete"],
      })
          .then((AMap) => {
              this.removeMarker();
              // 标记点
              this.setMapMarker(AMap);
          })
          .catch((err) => {
            // 错误
            console.log(err);
          });
    },
  },
};
</script>

<style>
.container {
  width: 100%;
  height: 100vh;
}
</style>

纯属记录自己新学的知识以防自己忘记了好查看,觉悟抄袭质疑,如有冒犯请多体谅,感谢!!!

### 集成高德地图实现标记点功能 要在 Vue3 项目中使用高德地图 API 实现地图打点功能,可以按照以下方法完成配置开发。 #### 1. 引入高德地图 JavaScript API 在项目的 `public/index.html` 文件中引入高德地图的官方脚本。通过指定版本号以及申请的应用密钥(AK),加载必要的库支持: ```html <script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=你的高德地图应用密钥"></script> ``` 此部分操作基于高德地图官方文档中的说明[^1]。 #### 2. 创建地图容器并初始化地图对象 在 Vue 组件模板中定义一个用于显示地图的 DOM 容器,并设置其样式以便于展示完整的地图区域。接着,在组件挂载阶段调用 AMap 初始化函数创建地图实例。 ```vue <template> <div id="mapContainer" class="map-container"></div> </template> <style scoped> .map-container { width: 100%; height: 500px; } </style> <script setup> import { onMounted } from 'vue'; onMounted(() => { const map = new window.AMap.Map('mapContainer', { zoom: 10, center: [116.397428, 39.90923], // 设置初始中心坐标 }); }); </script> ``` 上述代码片段展示了如何利用 Vue 的生命周期钩子来确保页面渲染完成后才执行地图初始化逻辑。 #### 3. 添加单个标记点到地图上 为了向地图添加特定位置上的标注图标,需借助 `AMap.Marker` 类型构建新的 Marker 对象并将之添加至已有的 Map 实例之中。 ```javascript const addMarkerToMap = (lngLat) => { const marker = new window.AMap.Marker({ position: lngLat, // 新建标记的位置参数 title: '目标地点', }); marker.setMap(map); }; // 示例调用方式 addMarkerToMap([116.397428, 39.90923]); ``` 这里实现了基本的地图标记功能,其中包含了经纬度信息作为输入参数传递给自定义封装的方法内部处理流程[^3]。 #### 4. 扩展:批量绘制多个标记点 如果存在大量地理位置需要一次性呈现在地图之上,则可以通过循环遍历数组形式的数据源逐一生成对应的 Markers 并加入集合管理类如 Clusterer 来优化视觉效果与性能表现。 ```javascript const batchAddMarkers = (pointsData) => { pointsData.forEach((pointInfo) => { const markerInstance = new window.AMap.Marker({ ...pointInfo.lnglat }); markerInstance.setMap(map); }); }; ``` 该扩展方案适用于复杂场景下的需求满足情况,同时也借鉴了相关资料里提到的技术思路。 --- ### 总结 综上所述,本文介绍了从基础环境搭建直至高级特性运用的一整套解决方案路径图解法,帮助开发者快速掌握如何在现代前端框架环境下高效接入第三方地理信息服务提供商所提供的强大工具集资源。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值