项目是uni-app , 功能模块首页需要集成地图, 目前采用高德地图
在这里插入图片描述

准备工作:

1.高德地图- 应用Key
2.高德地图 - 安全密钥
3.在 高德开发者平台 注册,选择开发者支持 -地图JS API 查看文档地图JS API

注意

高德地图在uni-app中使用是类似于vue中使用Echarts,图表库, 都需要在页面加载完成时的生命周期中使用Dom 节点。 然而在开发中右键检查/F12 下正常显示, 在真机测试中无法显示, 网上查阅说uniapp真机下没有Documnent 对象, 获取不到dom 元素,会报错

解决办法:renderjs
renderjs是一个运行在视图层的js。它比WXS更加强大。它只支持app-vue和web。

renderjs的主要作用有2个:

大幅降低逻辑层和视图层的通讯损耗,提供高性能视图交互能力
在视图层操作dom,运行 for web 的 js库
在原本的script 标签在写一个script 标签
renderjs 为视图层, 原script为逻辑层
<script module="test" lang="renderjs"></script>
在其中mounted:

if (window.AMap) {
				//todo 如果能访问到AMap直接初始化
				this.initAmap();
			} else {
				//todo 动态引入
				const script = document.createElement('script');
				script.src =
					"https://webapi.amap.com/maps?v=2.0&key=您申请的KEY";
				script.onload = () => {
					//todo 初始化地图
					this.initAmap();
				}
				document.head.appendChild(script);
			}

方法:

initAmap() {
				let that = this
				const map = new AMap.Map('amap', {
					resizeEnable: true,
					center: [116.397428, 39.90923],
					zoom: 13
				});
				map.clearMap(); // 清除地图覆盖物
				var markerList = [] //用来装标记点
				var List = [{
					icon: 'static/icons/Marker.png',
					position: [116.205467, 39.907761]
				}, {
					icon: 'static/icons/Marker.png',
					position: [116.368904, 39.913423]
				}, {
					icon: 'static/icons/Marker.png',
					position: [116.305467, 39.807761]
				}];

				let markerSrc = 'static/icons/Marker.png'
				List.forEach(function(item, index) {
					let marker = new AMap.Marker({
						map: map,
						icon: new AMap.Icon({
							image: markerSrc,
							imageSize: new AMap.Size(40, 40),
						}),
						position: [item.position[0], item.position[1]],
						offset: new AMap.Pixel(-13, -30),
						extData: {
							index,
						},
					});
					markerList.push(marker);
					marker.on('click', function(e) {
						let index1 = e.target.getExtData().index;
						markerList.forEach((markeritem) => {
							let index2 = markeritem.getExtData().index;
							let icon = e.target.getIcon();
							if (index1 === index2) {
								// that保存this
								//从renderjs到service层:通过this.$ownerInstance.callMethod()方法可以调用service中的方法,第一个参数是方法名,第二个参数是传过去的参数
								that.$ownerInstance.callMethod('checkShow', true)
								console.log(this.$ownerInstance, 'this')
								e.target.setIcon(
									new AMap.Icon({
										image: 'static/icons/MarkerSel.png', // Icon的图像
										imageSize: new AMap.Size(50, 50),
									})
								);
								that.markerInfoShow = true

							} else {
								markeritem.setIcon(
									new AMap.Icon({
										image: 'static/icons/Marker.png', // Icon的图像
										imageSize: new AMap.Size(40, 40),
									})
								);
							}
						})

					})
					// 将标记点数组放入Map
					map.add(markerList);
				});
			},

注意uniapp 中使用renderjs

高德地图API 东西很多, 项目用到在看吧

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐