注册高德获取key
高德开放平台官网地址点击搜索可以查询想用的服务 点击注册登录(手机号验证码)--> 应用管理---> 我的应用---> 添加key(一个服务平台选择小程序)(另外一个选择Web服务)
德地图定位和腾讯地图定位和uni.getLocation({type: 'gcj02',})【uniapp用的腾讯的】经纬度是一样的 个人认证开发者月配额150,000 (商用的话五万一年)【逆地理位置解析调用次数】 uniapp关于地图商用说明
一、uniapp高德地图获取详细位置
uniapp配置
manifest.json--->Web配置(勾选高德地图 填入key和秘钥)
manifest.json--->微信小程序配置--->微信小程序权限配置--->(勾选位置信息接口 填入描述)
manifest.json--->源码视图-->"requestDomain" : [ "restapi.amap.com" ],
"mp-weixin" : {
"requestDomain" : [ "https://restapi.amap.com", "https://lbs.qq.com" ],
"appid" : "您的小程序appid",
"setting" : {
"urlCheck" : false,
"minified" : true
},
"lazyCodeLoading" : "requiredComponents",
/* 新增隐私接口声明 */
"requiredPrivateInfos" : [ "getLocation" ],
/* 若需要定位权限,还需添加权限说明 */
"permission" : {
"scope.userLocation" : {
"desc" : "你的位置信息将用于定位打卡服务"
}
},
"usingComponents" : true
},
1. 即使微信小程序开启了不校验域名 也会真机运行失败:
打开 微信公众平台 → 左侧菜单 → 开发者与服务 → 开发管理 → 开发设置 → “服务器域名” 中设置request合法域名,添加restapi.amap.com 多个的话;号分割系统会自动添加;显示会自动换行(运营者可添加)直接粘贴都行
2. uniapp获取经纬度 注意事项官网地址
3. 高德网页版本逆地理位置解析(谷歌不能用)
//注意key 的类型必须是【Web服务】!!!
4.高德微信小程序逆地理位置解析
下载amap-wx官网地址 (第四步)
5. 预览报错
注意项目中只放置amap-wx.130.js文件 如果将整个AMapWX_SDK_V1.3.0文件夹下文件放置进去编译会报错
//获取经纬度
uni.getLocation({
type: 'gcj02',
success: function (res) {
console.log('当前位置的经度:' + res.longitude);
console.log('当前位置的纬度:' + res.latitude);
this.reverseGeocode(res)
}
});
/**
* 逆地理位置解析(经纬度转地址)
* @param {Object} location 包含经纬度的对象
*/
reverseGeocode(location){
// #ifdef H5 || APP
// H5和APP使用高德Web API
uni.request({
url: 'https://restapi.amap.com/v3/geocode/regeo',
data: {
location: `${location.longitude},${location.latitude}`,
key: 'Web服务key值',
extensions: 'all',
output: 'json'
},
success(res) {
},
fail: (err) => {
},
})
// #endif
// #ifdef MP-WEIXIN
// 小程序使用高德微信JSAPI
const amap = require('@/static/AMapWX_SDK_V1.3.0/amap-wx.130.js')
const amapPlugin = new amap.AMapWX({
key: '小程序key值'
})
amapPlugin.getRegeo({
location: `${location.longitude},${location.latitude}`,
success: (res) => {
if (res.length > 0) {
resolve(res[0].regeocodeData)
} else {
reject(new Error('逆地理编码失败'))
}
},
fail: reject
})
// #endif
}
二、vue2使用高德地图实现搜索定位和点击获取经纬度和地址地图JSAPI2.0官网地址
1. 下载高德地图的依赖
npm i @amap/amap-jsapi-loader
2. 注册高德地图获取key和秘钥
点击注册登录(手机号验证码)--> 应用管理---> 我的应用---> 添加key(选择Web服务(JS API)
可以在 .env 文件中添加VUE_APP_KEY='key值' VUE_APP_SECURITY='密钥'
组件代码:
<template>
<el-row :gutter="15" class="container">
<!-- 地图 -->
<div class="mapbox">
<div class="search_box">
<div class="label">地址搜索</div>
<el-input v-model="input" placeholder="请输入内容" id="tipinput"></el-input>
</div>
<div ref="gaode_Map" id="gaode_Map"></div>
</div>
</el-row>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
window._AMapSecurityConfig = {
securityJsCode: process.env.VUE_APP_SECURITY,
};
export default {
props: {
initData: {
type: Array,
default: () => [116.397428, 39.90923], // 默认北京坐标
},
},
data() {
return {
district: null,
polygons: [],
form: {},
dataForm: {
kqName: undefined,
kqLocation: undefined,
kqLongitude: undefined,
kqLatitude: undefined,
kqWorkUnit: undefined,
cronkqAccredit: [],
kqValidCardRange: undefined,
},
input: "",
map: null,
auto: null,
placeSearch: null,
lnglat: [],
markers: [],
position: {
longitude: null,
latitude: null,
address: "",
},
circleMarker1: null,
marker: null,
geocoder: null, // 复用 Geocoder 实例
province: "",
city: "",
};
},
mounted() {
AMapLoader.reset();
this.initMap();
},
beforeUnmount() {
if (this.map) {
this.map.off("click", this.clickMapHandler);
this.map.destroy();
this.map = null; // 清空引用
}
},
methods: {
dataFormSubmit() {
this.setCircle(this.lnglat, this.dataForm.kqValidCardRange);
},
setCircle(lnglat, radius = 500, fillColor = "#ff00ff") {
if (this.marker) {
this.map.remove(this.marker);
}
if (this.circleMarker1) {
this.map.remove(this.circleMarker1);
}
this.marker = new AMap.Marker({ position: lnglat });
this.marker.setMap(this.map);
this.circleMarker1 = new AMap.CircleMarker({
map: this.map,
center: lnglat,
radius,
fillColor,
});
this.circleMarker1.setMap(this.map);
},
searchMap() {
this.auto = new AMap.AutoComplete({ input: "tipinput" });
this.placeSearch = new AMap.PlaceSearch({ map: this.map });
this.auto.on("select", this.selectSite);
},
// 选择地址
selectSite(e) {
console.log(e);
if (e.poi.location) {
const lnglat = [e.poi.location.lng, e.poi.location.lat];
console.log('选择地址', lnglat);
this.lnglat = lnglat;
this.setCircle(lnglat);
this.placeSearch.setCity(e.poi.adcode);
this.placeSearch.search(e.poi.name);
this.geocoder.getAddress(lnglat, (status, result) => {
if (status === "complete" && result.regeocode) {
const addrComp = result.regeocode.addressComponent;
this.form = {
province: addrComp.province,
city: addrComp.city,
address: e.poi.name,
coordinate: `${e.poi.location.lng},${e.poi.location.lat}`,
};
console.log(this.form);
this.dataForm.kqLongitude = e.poi.location.lng;
this.dataForm.kqLatitude = e.poi.location.lat;
this.dataForm.kqLocation = e.poi.name
this.$emit("updateLocation", this.dataForm);
} else {
console.log("查询地址失败");
}
});
} else {
this.placeSearch.setCity(e.poi.adcode)
this.placeSearch.search(e.poi.name) //关键字查询查询
// this.drawBounds(e.poi.name)
this.map.setZoom(16, true, 1)
}
},
feedBack(msg, feedBackType) {
this.$message({
showClose: true,
message: msg,
type: feedBackType
})
},
// 行政区区域划分
drawBounds(newValue) {
//加载行政区划插件
if (!this.district) {
//实例化DistrictSearch
var opts = {
subdistrict: 1, //获取边界不需要返回下级行政区
extensions: 'all', //返回行政区边界坐标组等具体信息
level: 'district' //查询行政级别为 市
}
this.map.plugin(['AMap.DistrictSearch'], () => {
this.district = new AMap.DistrictSearch(opts)
})
// this.district = new AMap.DistrictSearch(opts)
}
//行政区查询
this.district.search(newValue, (status, result) => {
console.log(result)
if (result != null) {
this.feedBack('区域搜索成功', 'success')
if (this.polygons != null) {
this.map.remove(this.polygons) //清除上次结果
this.polygons = []
}
var bounds = result.districtList[0].boundaries
if (bounds) {
for (var i = 0, l = bounds.length; i < l; i++) {
//生成行政区划polygon
var polygon = new AMap.Polygon({
strokeWeight: 1,
path: bounds[i],
fillOpacity: 0.4,
fillColor: '#80d8ff',
strokeColor: '#0091ea'
})
this.polygons.push(polygon)
}
}
this.map.add(this.polygons)
this.map.setFitView(this.polygons) //视口自适应
} else {
this.feedBack('区域搜索失败', 'error')
}
})
},
clickMapHandler(e) {
console.log(e);
const lng = e.lnglat.getLng();
const lat = e.lnglat.getLat();
this.dataForm.kqLongitude = lng;
this.dataForm.kqLatitude = lat;
this.lnglat = [lng, lat];
this.setCircle(this.lnglat);
this.geocoder.getAddress(this.lnglat, (status, result) => {
if (status === "complete" && result.regeocode) {
const regeo = result.regeocode;
this.dataForm.kqLocation = regeo.formattedAddress;
this.dataForm.localName = regeo.addressComponent.neighborhood || "";
this.input = regeo.formattedAddress;
this.position = {
longitude: lng,
latitude: lat,
address: regeo.formattedAddress,
};
this.$emit("updateLocation", this.dataForm);
} else {
console.log("查询地址失败");
}
});
},
initMap() {
AMapLoader.load({
key: process.env.VUE_APP_KEY,
version: "2.0",
plugins: ['AMap.Scale', 'AMap.ToolBar',"AMap.AutoComplete", 'AMap.ControlBar', "AMap.PlaceSearch", "AMap.Geocoder"],
})
.then((AMap) => {
this.map = new AMap.Map("gaode_Map", {
viewMode: "3D",
zoom: 18,
center: this.initData,
resizeEnable: true,
});
this.geocoder = new AMap.Geocoder({
// city 指定进行编码查询的城市,支持传入城市名、adcode 和 citycode
city: '全国'
});
this.map.addControl(new AMap.Scale()); //比例尺
this.map.addControl(new AMap.ToolBar()); //缩放工具条
this.map .addControl(new AMap.ControlBar()); //控制罗盘
this.setCircle(this.initData);
this.searchMap();
this.map.on("click", this.clickMapHandler);
})
.catch(() => {
this.$message.error("地图加载失败");
});
},
},
};
</script>
<style lang="less">
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
.mapbox {
width: 100%;
}
}
.search_box {
display: flex;
justify-content: flex-start;
align-items: center;
height: 50px;
margin-bottom: 20px;
.label {
color: #000;
width: 100px;
}
}
#gaode_Map {
overflow: hidden;
width: 100%;
height: 350px;
margin: 0;
margin-bottom: 50px;
}
.amap-sug-result {
z-index: 2999 !important;
}
</style>
组件调用示例
<template>
<Map ref="map" v-if="open" :initData="maprops" @updateLocation="updateLocation"></Map>
</template>
<script>
import Map from "@/components/GaodeMap.vue";
export default {
components: { Map },
data() {
return {
title: "",
open: false,
maprops: [] // 初始化为空数组
};
},
methods: {
handleAdd() {
this.open = true;
this.title = "添加打卡地点";
this.maprops = [113.634443, 34.743675]
},
updateLocation(mapData) {
console.log("更新后的位置信息:", mapData);
},
handleUpdate(row) {
this.title = "修改打卡地点";
this.maprops = [ row.longitude,row.latitude]
},
}
};
</script>