1.申请key
高德开放平台 | 高德地图API注册申请,在管理应用里添加应用,然后根据需求申请高德地图的Key
2、新建一个动态加载高德地图的js。
export default function loadMap (key, plugins, v = '1.4.14') {
return new Promise(function (resolve, reject) {
if (typeof AMap !== 'undefined') {
// eslint-disable-next-line no-undef
resolve(AMap)
return true
}
window.onCallback = function () {
// eslint-disable-next-line no-undef
resolve(AMap)
}
let script = document.createElement('script')
// script.type = 'text/javascript'
script.src = `https://webapi.amap.com/maps?v=${v}&key=${key}&plugin=${plugins}&callback=onCallback`
script.onerror = reject
document.head.appendChild(script)
})
}
3、获取定位
import Gaode_loadMap from '../../common/js/gaode_loadMap'; //引入加载地图的js
Gaode_loadMap('webjs_key', ['AMap.Geolocation'], '1.4.14')
.then(AMap => {
var map = AMap.plugin('AMap.Geolocation', function() {
var geolocation = new AMap.Geolocation({
// enableHighAccuracy: true,// 是否使用高精度定位,默认:true
// 设置定位超时时间,默认:无穷大
timeout: 6000
});
geolocation.getCurrentPosition();
AMap.event.addListener(geolocation, 'complete', onComplete);
AMap.event.addListener(geolocation, 'error', onError);
function onComplete(data) {
// console.log('gen geo data===' + JSON.stringify(data));
state.gd_loction = data.position
console.log('state.gd_loction===' + state.gd_loction);
let geo = state.gd_loction.toString().split(',')
state.lnt = geo[0]
state.lat = geo[1]
uni.hideLoading();
}
function onError(data) {
console.log(data);
uni.showModal({
title: '',
content: '未获取到定位请前往选择',
showCancel: false,
cancelText: '取消',
confirmText: '确定',
success: res => {
if (res.confirm) {
uni.hideLoading()
toChooseAdr()
}
},
fail: () => {},
complete: () => {}
});
// 定位出错
}
});
})
.catch(() => {
console.log('地图加载失败!');
});
4、根据关键字获得地址
参考文档 搜索POI-API文档-开发指南-Web服务 API | 高德地图API
uni.request({
url: 'https://restapi.amap.com/v3/assistant/inputtips?output=JSON&city=010&type=poi&keywords=关键字' + '&key=web服务Key',
method: 'GET',
data: {},
success: res => {
state.addressList = []
let list = res.data.tips
//有时候会返回空名称
state.addressList = list.filter(item => item.address.length > 0)
},
fail: () => {},
complete: () => {}
});
5、小程序获取定位
相关下载-微信小程序插件 | 高德地图API 下载高德地图提供的插件
import amapFile from '@/utils/amap-wx.130.js' //引入
letmyAmapFun = new amapFile.AMapWX({
key: 'key'
})
let that = this
myAmapFun.getRegeo({
success: data => {
//成功回调
console.log(data)
},
fail: info => {
//失败回调
console.log(info)
}
})