本项目是H5端,APP端地图的使用方法请参考我的另一篇博客uniapp,map地图组件打包原生APP
首先到高德地图API,申请web端key

参考高德H5端教程开始写代码高德地图JS API
1、准备工作,会提示你先引入下边这块代码
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=您申请的key值"></script>
我的项目是uniapp项目,在自定义的html引入会报错,个人感觉可能是加载顺序的问题,最后修改成
import maps from '../../static/maps.js'
关于maps.js文件是怎么来的,第一步准备工作的src链接,直接打开,将这个js文件保存到本地maps.js并引用就可以。
2、定义dom
<view id="container"></view>
3、为地图容器指定宽高
#container {
width: 750rpx;
height: 750rpx;
}
4、初始化地图控件,需要放在this.$nextTick函数内,否则会报错(之前是按照官方的写法window.onLoad,测试也可以,过了段时间不行了,不知道什么原因)
this.$nextTick(() => {
let _this = this;
_this.map = new AMap.Map('container', {
zoom: 15, //缩放级别
resizeEnable: true, //自动定位
});
})
初始化完成如下图

uniapp data中的变量,下边的操作会向变量中赋值
data() {
return {
map: null,
address0: {
}, //起点信息
address1: {
}, //终点信息
star: [], //起点
end: [], //终点
markers: [], //点标记
routes: {
}, //路线距离时间信息记录
}
},
5、地图已经调出来了,现在应该获取定位,并在在地图上定位标记点
AMap.plugin('AMap.Geolocation', function() {
uni.showLoading({
title: '系统正在定位'
});
var geolocation = new AMap.Geolocation({
enableHighAccuracy: true, //是否使用高精度定位,默认:true
timeout: 10000, //超过10秒后停止定位,默认:5s
buttonPosition: 'RB', //定位按钮的停靠位置
buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
});
_this.map.addControl(geolocation);
geolocation.getCurrentPosition(function(status, result) {
if (status == 'complete') {
//这个地方的result,可能会出现报错:获得地理定位时间。得到ipLocation成功。获取地址失败,请检查您的密钥或网络。
//可能是密匙申请错了,重新申请密匙,生成maps.js文件。
console.log(result)
uni.hideLoading();
uni.showToast({
title: '定位成功',
});
let res = {
name: result.formattedAddress,
latitude: result.position.lat,
longitude: result.position.lng,
}
let marker0 = new AMap.Marker({
map: _this.map,
position: [res.longitude, res.latitude], //位置
icon: '/static/star.png', // 添加 Icon 图标 URL
offset: new AMap.Pixel(-15, -42),//偏移量
});
_this.markers[0] = marker0; //添加 起点 标记
_this.address0 = res; //起点数据
_this.star = [res.longitude, res.latitude]; //起点经纬度
} else {
uni.hideLoading();
uni.showToast({
title: '定位失败,请手动选择出发地',
}

本文详细介绍了如何在uniapp项目中使用高德地图API实现地图显示、定位、选择地点及路线规划等功能,包括引入地图SDK、初始化地图、获取定位、选择起点终点和规划路线的步骤。
最低0.47元/天 解锁文章
3183

被折叠的 条评论
为什么被折叠?



