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();
}
一个在学习的开发者,勿喷,欢迎交流