百度地图api H5-uniapp 1.创建自定义控件 2.实时更新用户坐标

--此篇是记录创建自定义控件的方法--

自定义控件事件为 点击后回到用户当前视角 ,更简单的解决方式应该可以创建一个标签直接定位到需要位置 ,就不需要创建 自定义控件 这么麻烦。

使用的data参数

	data() {
		return {
			map: null,//地图对象
			currentPosition: {//用户点坐标
				longitude: null,
				latitude: null,
			},
			currentUserPositionIcon: {//地图渲染的用户的文字和icon对象
				marker: null,
				label: null,
			},
		}
	},

引入js

		createScript(url) {
			return new Promise((resolve, reject) => {
				var script = document.createElement('script')
				script.type = 'text/javascript'
				script.src = url
				script.onload = () => resolve()
				script.onerror = () => reject()
				document.head.appendChild(script)
			})
		},
		initBaiDuMap() {
			const ak = ''

			if (typeof window.BMap === 'function') {
				this.initMap()
			} else {
				window.init = () => this.initMap()
				this.createScript(`https://api.map.baidu.com/api?v=3.0&ak=${ak}&callback=init`)
			}

初始化

//初始化	
	async initMap() {
			let mapConstructor
			// myMap 要渲染地图的view的id
//data 中map 参数
			this.map = new BMap.Map('myMap')
			mapConstructor = BMap
			this.centerAndZoomCustomControl(this.map)
			const updateMap = async () => {
				// 清除现有的覆盖物
				this.map.clearOverlays()
				await this.addCurrentUserPoint() //获取坐标 创建渲染当前用户坐标
				let latitude = parseFloat(this.currentPosition.latitude)
				let longitude = parseFloat(this.currentPosition.longitude)
				let point = new BMap.Point(longitude, latitude)
				this.map.centerAndZoom(point, 15) // 设置中心点

				var scaleCtrl = new BMap.ScaleControl() // 添加比例尺控件
				// 添加到地图中
				this.map.addControl(scaleCtrl)
				var zoomCtrl = new BMap.NavigationControl({
					anchor: BMAP_ANCHOR_TOP_RIGHT,
				}) // 添加缩放控件
				this.map.addControl(zoomCtrl)
				// 创建城市选择控件
				var cityControl = new BMap.CityListControl({
					anchor: BMAP_ANCHOR_TOP_LEFT,
					offset: new BMap.Size(10, 5),
				})
				this.map.addControl(cityControl)
			}
			updateMap() // 初始化地图
		},

创建自定义控件   事件为:点击后视角回到用户当前坐标
 

		// 创建自定义控件
		async centerAndZoomCustomControl(map) {
			function CustomControl() {
				this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT
				this.defaultOffset = new BMap.Size(8, 100)
			}
			// 继承控件基类
			CustomControl.prototype = new BMap.Control()
			// 初始化控件
			CustomControl.prototype.initialize = function (map) {
				var div = document.createElement('div')
				div.style.width = '40px'
				div.style.height = '40px'
				div.style.backgroundImage = "url('static/images/user4.png')"
				div.style.backgroundSize = '100% 100%'
				div.style.cursor = 'pointer'
				// 添加点击事件
				div.onclick = async function () {
					await this.updataUserAddress()
					let latitude = parseFloat(this.currentPosition.latitude)
					let longitude = parseFloat(this.currentPosition.longitude)
					let point = new BMap.Point(longitude, latitude)
					map.centerAndZoom(point, 15) // 设置中心点
				}.bind(this)
				// 添加到地图容器中
				map.getContainer().appendChild(div)
				return div
			}.bind(this)
			// 创建控件实例
			var customControl = new CustomControl()
			// 添加到地图中
			map.addControl(customControl)
		},

当前用户坐标实时更新   若视角实时移动(中心点未发生改变的情况  即用户未修改地图视角)

		async addCurrentUserPoint() {
			const center = this.map.getCenter()
			let copyCurrentPosition = JSON.parse(JSON.stringify(this.currentPosition))
			await this.updataUserAddress()
//比对中心点是否发生改变 若未改变则根据 当前位置重新设置中心点
			if (center.lng == copyCurrentPosition.longitude && center.lat == copyCurrentPosition.latitude) {
				let latitude = parseFloat(this.currentPosition.latitude)
				let longitude = parseFloat(this.currentPosition.longitude)
				let point = new BMap.Point(longitude, latitude)
				this.map.centerAndZoom(point, 15) // 设置中心点
			}
			//删除上一个定位
			this.map.removeOverlay(this.currentUserPositionIcon.marker)
			this.map.removeOverlay(this.currentUserPositionIcon.label)
			let mapConstructor = BMap
			const mPoint = new mapConstructor.Point(this.currentPosition.longitude, this.currentPosition.latitude)
			var myIcon = new mapConstructor.Icon(`static/images/user4.png`, new mapConstructor.Size(60, 60))
			myIcon.imageSize = new mapConstructor.Size(60, 60)
			var marker = new mapConstructor.Marker(mPoint, {
				icon: myIcon,
				offset: new mapConstructor.Size(0, 0),
			})
			this.map.addOverlay(marker)
//保留这个对象  删除时需要
			this.currentUserPositionIcon.marker = marker
			// 创建文字标注
			const label = new mapConstructor.Label('当前位置', {
				position: {
					lng: this.currentPosition.longitude,
					lat: this.currentPosition.latitude,
				},
				offset: new mapConstructor.Size(-25, +28),
			})
			label.setStyle({
				color: '#000',
				fontSize: '12px',
				height: '20px',
				lineHeight: '20px',
				border: '1px none #000',
				backgroundImage: 'none',
				opacity: 0.85,
			})
			this.map.addOverlay(label)
//保留这个对象  删除时需要
			this.currentUserPositionIcon.label = label
//用户当前位置 实时更新  
			setTimeout(() => {
				this.addCurrentUserPoint()
			}, 5000)
		},

上述代码更新 更新坐标定位的函数

		async updataUserAddress() {
			try {
				const res = await this.getParseAddress()
				this.currentPosition.longitude = Number(res?.longitude)
				this.currentPosition.latitude = Number(res?.latitude)
			} catch (e) {
				console.log('e', e)
				uni.showToast({
					title: e,
					icon: 'none',
				})
			}
		},
		getParseAddress() {
			return new Promise((resolve, reject) => {
				uni.getLocation({
					type: 'wgs84',
					isHighAccuracy: true,
					success: (res) => {
						resolve(res)
					},
					fail: (err) => {
						reject('获取位置失败!请检查定位权限和定位是否开启!并尝试重新获取!')
					},
				})
			})
		},

参考 api文档

百度地图JSAPI 2.0类参考  自定义控件创建

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值