Vue3页面配置高德地图,获取位置

本文介绍了如何在Vue3项目中配置高德地图,包括申请APIkey、在页面上显示地图并标记位置、搜索提示以及调用后台接口获取经纬度对应的地址。

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

Vue3页面配置高德地图,获取位置

一、功能介绍

1.1.打开地图显示前区域,并标记
1.2.点击地图位置,标记并方法显示
1.3.搜索提示,显示提示数据,跳转显示对应位置。

二、申请高德地图的key

2.1.百度搜索登录高德地图平台,注册用户登录。
在这里插入图片描述2.2.登录后,需先认证成为开发者
2.3.在控制台中,申请相关的应用,获取key值

三、Vue页面

1.1.页面全部代码

<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="" prop="">
        <div id="containerMap" style="width: 500px; height: 500px;z-index: 1;position: relative">
          <div class="info" style="z-index: 2;position: absolute">
            <div class="input-item">
              <div class="input-item-prepend">
                <span class="input-item-text" style="width:100px;">请输入关键字</span>
              </div>
              <input id='tipinput' type="text" v-model="keyword" @input="iptchange()"/>
              <ul>
                <li v-for="(item,index) in (itemsAddress)" :key="index" @click="toAssignAddress(item)">
                  {{item.name}}
                </li>
              </ul>
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitMapForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">

  import { TakeShopApi, TakeShopVO } from '@/api/takeshop/takeshop'
  import AMapLoader from '@amap/amap-jsapi-loader';
  import { onMounted, onUnmounted } from "vue";
  import axios from "axios";

  /** 地图 */
  defineOptions({ name: 'MaoForm' })

  const message = useMessage() // 消息弹窗

  const dialogVisible = ref(false) // 弹窗的是否展示
  const dialogTitle = ref('') // 弹窗的标题
  const formLoading = ref(false) // 表单的加载中:1)修改时的数据加载;2)提交的按钮禁用
  const formType = ref('') // 表单的类型:create - 新增;update - 修改
  const keyword = ref('')
  const formData = ref({
    address:undefined,
    longitude:undefined,
    latitude:undefined
  })
  const formRules = reactive({
  })
  const formRef = ref() // 表单 Ref

  let map = null;

  const itemsAddress = ref([])

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

  /** 打开弹窗 */
  const toMapForm = async (type: string, id?: number) => {
    dialogVisible.value = true
    dialogTitle.value = "地图"
    formType.value = type
    resetForm()
    newMap()
    // 修改时,设置数据
    if (id) {
      formLoading.value = true
      try {
        formData.value = await TakeShopApi.getTakeShop(id)
      } finally {
        formLoading.value = false
      }
    }
  }
  defineExpose({ toMapForm }) // 提供 open 方法,用于打开弹窗
  /** */
  function newMap(){
    window._AMapSecurityConfig = {
      securityJsCode: "", // 密钥
    };
   //key: 申请好的Web端开发者Key,首次调用 load 时必填
   //version: 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
   //plugins: 需要使用的的插件列表,如比例尺'AMap.Scale'等
    AMapLoader.load({
      key: "", 
      version: "2.0", 
      plugins: ['AMap.AutoComplete','AMap.PlaceSearch','AMap.Geocoder'], 
    })
      .then((AMap) => {
        map = new AMap.Map("containerMap", {
          // 设置地图容器id
          zoom: 11, // 初始化地图级别
          center: [112.144146,32.042426], // 初始化地图中心点位置NPM
          resizeEnable: true,
        });
        //监听用户的点击事件
        map.on('click', e => {
          let lng = e.lnglat.lng
          let lat = e.lnglat.lat
          const marker = new AMap.Marker({
            position: new AMap.LngLat(lng, lat),   // 经纬度对象,也可以是经纬度构成的一维数组[116.39, 39.9]
            title: ''
          });
          map.clearMap();
          map.add(marker)
          var geocoder = new AMap.Geocoder({
            // city 指定进行编码查询的城市,支持传入城市名、adcode 和 citycode
            city: '全国'
          })
          let lnglat = [lng,lat]
          let address = lng +"," +lat
          formData.longitude = lng
          formData.latitude = lat
          toMapAddress(address)
        })

      })
      .catch((e) => {
        console.log(e);
      });
  };

  //搜索
  const iptchange = async () =>{
    var key = ''
    axios({
      methods: 'get',
      url: `https://restapi.amap.com/v3/assistant/inputtips?key=${key}&keywords=${keyword.value}`
    }).then(res => {
      itemsAddress.value = res.data.tips
    })
  }

  //定位
  const toAssignAddress = async (item) => {
    console.log("item",item)
    var geocoder = new AMap.Geocoder({
      // city 指定进行编码查询的城市,支持传入城市名、adcode 和 citycode
      city: item.adcode
    })
    var latLngArr =  item.location.split(",");
    var latAddress = new AMap.LngLat(Number(latLngArr[0]), Number(latLngArr[1]),)
    geocoder.getAddress(latAddress, function(status, result) {
      if (status === 'complete' && result.info === 'OK') {
        // result中对应详细地理坐标信息
        //清除之前的标记
        map.clearMap();
        const marker = new AMap.Marker({
          position: latAddress,   // 经纬度对象,也可以是经纬度构成的一维数组[116.39, 39.9]
          title: ''
        });
        map.add(marker)
        map.setCenter(latLngArr);
        map.setFitView()
        let address = Number(latLngArr[0]) +"," +Number(latLngArr[1])
        formData.longitude = Number(latLngArr[0])
        formData.latitude = Number(latLngArr[1])
        toMapAddress(address)
      }
    })
  }

  /** 根据经纬度获取地址,此处调用的是后台接口*/
  const toMapAddress = async (address) => {
    const data = await TakeShopApi.toMapAddress(address)
    if(data.code == 0){
      formData.address = data.data
    }
  }

  /** 提交地图 */
  const emit = defineEmits(['getData']) // 定义 success 事件,用于操作成功后的回调
  const submitMapForm = async () => {
    // 提交请求
    formLoading.value = true
    try {
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('getData',formData)
    } finally {
      formLoading.value = false
    }
  }

  /** 重置表单 */
  const resetForm = () => {
    formData.value = {
      address:undefined
    }
    formRef.value?.resetFields()
  }
</script>

<style>

</style>
三、Java后台方法

1.根据经纬度获取地址

	@GetMapping("/toMapAddress")
    public CommonResult toMapAddress(@RequestParam(name="address",required = true) String address){
        String queryUrl  = "https://restapi.amap.com/v3/geocode/regeo?output=xml&location=" + address +
                "&key="自己的key"&radius=1000&extensions=all";
        String queryResult = getResponse(queryUrl );
        // 将获取结果转为json数据
        JSONObject jsonObject = new JSONObject(queryResult);
        JSONObject responseObj = new JSONObject(jsonObject.get("response"));
        JSONObject regeocodeObj = new JSONObject(responseObj.get("regeocode"));
        if (responseObj.get("status").toString().equals("1")) {
            if (regeocodeObj.size() > 0) {
                // 在regeocode中拿到 formatted_address 具体位置
                return success(regeocodeObj.get("formatted_address").toString());
            } else {
                throw new RuntimeException("未找到相匹配的地址!");
            }
        }else{
            return null;
        }
    }

2.http请求高德地图API

private String getResponse(String queryUrl ) {
        // 用JAVA发起http请求,并返回json格式的结果
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(queryUrl);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

一个在学习的开发者,勿喷,欢迎交流

### Vue3 集成高德地图 API 获取当前地理位置 要在 Vue3 项目中集成高德地图并实现获取当前地理位置的功能,可以通过以下方式完成: #### 前期准备 首先需要注册高德开发者账号,并申请相应的 API Key。这是使用高德地图服务的前提条件[^1]。 #### 安装依赖 安装 `vue-amap` 插件以便于在 Vue3 中更方便地操作高德地图: ```bash npm install vue-amap ``` #### 初始化配置 通过 `VueAMap.initAMapApiLoader` 方法加载高德地图的 JavaScript API 并进行必要的初始化配置。以下是完整的代码示例: ```javascript <template> <div id="mapContainer" style="width: 100%; height: 500px;"></div> </template> <script> import { defineComponent, onMounted } from &#39;vue&#39;; import VueAMap from &#39;@vuemap/vue-amap&#39;; export default defineComponent({ name: &#39;AmapLocation&#39;, setup() { let map = null; const initMap = async () => { await VueAMap.initAMapApiLoader({ key: &#39;你的高德地图API Key&#39;, // 替换为自己的Key plugin: [&#39;AMap.Geolocation&#39;], // 加载定位插件 v: &#39;1.4.15&#39; // 设置SDK版本号 }); map = new AMap.Map(&#39;mapContainer&#39;, { zoom: 12, center: [116.397428, 39.90923], // 默认中心点坐标 }); getLocation(); }; const getLocation = () => { const geolocation = new AMap.Geolocation({ enableHighAccuracy: true, // 是否启用高精度定位,默认true timeout: 10000, // 超过10秒后停止定位,默认:无穷大 buttonPosition: &#39;RB&#39;, // 控制按钮停靠位置,默认:LB(左下角) }); map.addControl(geolocation); geolocation.getCurrentPosition((status, result) => { if (status === &#39;complete&#39;) { addMarker(result.position); // 成功回调函数 } else { console.error(&#39;定位失败:&#39;, result); } }); }; const addMarker = (position) => { const marker = new AMap.Marker({ position: position, // 将定位点设为标记的位置 title: &#39;当前位置&#39; }); map.add(marker); // 添加标记到地图上 map.setCenter(position); // 移动地图视口至定位点 }; onMounted(() => { initMap(); // 页面挂载完成后执行地图初始化逻辑 }); return {}; }, }); </script> ``` 此代码实现了如下功能: - 使用 `VueAMap.initAMapApiLoader` 进行高德地图 API 的初始化配置[^2]。 - 创建地图容器并通过 `new AMap.Map()` 实例化地图对象。 - 利用 `AMap.Geolocation` 插件获取用户的当前地理位置信息。 - 如果定位成功,则调用 `addMarker()` 函数,在地图上添加一个标记表示用户所在位置,并将地图中心移动至此处。 #### 注意事项 如果遇到错误提示类似于 `Uncaught Error: Invalid Object: LngLat(NaN, NaN)`,可能是由于未正确传入有效的经纬度参数引起的。需确保传递给 `LngLat` 构造器的数据均为有效数值[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值