高德地图常用方法封装

在开发中,经常用到高德地图,于是总结了一些常用的方法进行封装

动态创建高德脚本

创建 createAMap.js

import { config } from '../config'
import Bus from '../eventBus.js'
class CreateAMap {
	constructor() {
		this.init()
	}
	init () {
		window.initAMap = () => {
			Bus.$emit('AMapIsExist', null)
		}
		let plugins = 'AMap.Driving,AMap.Geocoder,AMap.Walking,AMap.Riding,AMap.Transfer,AMap.Geolocation'
		let script = document.createElement('script')
		script.type = 'text/javascript'
		script.async = true
		script.src = `https://webapi.amap.com/maps?v=1.4.15&callback=initAMap&key=${config.amapKey}&plugin=${plugins}`
		// script.onerror = reject
		document.head.appendChild(script)
	}
}
let createAMap = new CreateAMap()
export { createAMap }

vue 页面使用

import Bus from '../../common/eventBus.js'
import { createAMap } from '../../common/AMap/create'

// 在mounted里try catch
try {
  if (AMap) {
    this.amapLoad()
  }
} catch {
  Bus.$on('AMapIsExist', this.amapLoad)
}

封装高德常用的方法

amap.js 如下:

/**
 * @Description: 进一步封装高德常用的方法
 * @Author: MuYi086
 * @Email: 1258947325@qq.com
 * @Blog: https://github.com/MuYi086/blog
 */
class AMAP {
  constructor () {
    this.init()
  }
  init () {
		// 绑定div对象
		let containerId = 'gd-container'
		// 获取最新map对象
		this.newMap = (center) => {
			if (center) {
				return new AMap.Map(containerId, {
					resizeEnable: true,
					center: center, // 地图中心点
					zoom: 13
				})				
			} else {
				return new AMap.Map(containerId, {
					resizeEnable: true,
					zoom: 13
				})	
			}
    }
		/**
		 * 定位
		 * params: {success: '成功回调', fail: '失败回调'}
		 */
		this.location = (success, fail) => {
			var map = this.newMap()
			var geolocation = AMap.Geolocation({	
				enableHighAccuracy: true,//是否使用高精度定位,默认:true
				timeout: 200,          //超过10秒后停止定位,默认:无穷大
				maximumAge: 0,           //定位结果缓存0毫秒,默认:0
				convert: true,           //自动偏移坐标,偏移后的坐标为高德坐标,默认:true
				showButton: true,        //显示定位按钮,默认:true
				buttonPosition: 'RB',    //定位按钮停靠位置,默认:'LB',左下角
				buttonOffset: new AMap.Pixel(10, 120),//定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
				showMarker: true,        //定位成功后在定位到的位置显示点标记,默认:true
				showCircle: true,        //定位成功后用圆圈表示定位精度范围,默认:true
				panToLocation: true,     //定位成功后将定位到的位置作为地图中心点,默认:true
				zoomToAccuracy: true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
			})
			map.addControl(geolocation)
			geolocation.getCurrentPosition(function(status, result){
				if (status == 'complete'){
					success(result)
				} else {
					fail(result)
				}
			})
		}
		/**
		 * 路径导航:汽车
		 * params: {center: '中心坐标', startLngLat: '开始坐标', endLngLat: '结束坐标', success: '成功回调', fail: '失败回调'}
		 */
		this.carPathNavigation = (center, startLngLat, endLngLat, success, fail) => {
			var map = this.newMap(center)
			var driving = new AMap.Driving({
				map: map
			})
			driving.search(new AMap.LngLat(startLngLat[0], startLngLat[1]), new AMap.LngLat(endLngLat[0], endLngLat[1]), function(status, result) {
				// result 即是对应的驾车导航信息,相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
				if (status === 'complete') {
					success(result)
				} else {
					fail(result)
				}
			})
		}
		/**
		 * 路径导航:步行
		 * params: {center: '中心坐标', startLngLat: '开始坐标', endLngLat: '结束坐标', success: '成功回调', fail: '失败回调'}
		 */
		this.walkPathNavigation = (center, startLngLat, endLngLat, success, fail) => {
			var map = this.newMap(center)
			var walking = new AMap.Walking({
				map: map
			})
			walking.search(startLngLat, endLngLat, function(status, result) {
				if (status === 'complete') {
					success(result)
				} else {
					fail(result)
				}
			})
		}
		/**
		 * 路径导航:骑行
		 * params: {center: '中心坐标', startLngLat: '开始坐标', endLngLat: '结束坐标', success: '成功回调', fail: '失败回调'}
		 */
		this.bikePathNavigation = (center, startLngLat, endLngLat, success, fail) => {
			var map = this.newMap(center)
			var riding = new AMap.Riding({
				map: map
			})
			riding.search(startLngLat, endLngLat, function(status, result) {
				if (status === 'complete') {
					success(result)
				} else {
					fail(result)
				}
			})
		}
		/**
		 * 路径导航:公交
		 * params: {center: '中心坐标', startLngLat: '开始坐标', endLngLat: '结束坐标', success: '成功回调', fail: '失败回调'}
		 */
		this.bikePathNavigation = (center, startLngLat, endLngLat, success, fail) => {
			this.parseCoordinate(center, (res) => {
				// 坐标解析出城市
				let city = res.regeocode.addressComponent.city
				var map = this.newMap(center)
				var transOptions = {
					map: map,
					city: city,
					policy: AMap.TransferPolicy.LEAST_TIME
				}
				transfer.search(new AMap.LngLat(startLngLat[0], startLngLat[1]), new AMap.LngLat(endLngLat[0], endLngLat[1]), function(status, result) {
					if (status === 'complete') {
						success(result)
					} else {
						fail(result)
					}
				})
			}, (err) => {
				console.log(err)
			})
		}
		/**
		 * 坐标=>地址
		 * params: {center: '中心坐标', success: '成功回调', fail: '失败回调'}
		 */
		this.parseCoordinate = (center, success, fail) => {
			var geocoder = new AMap.Geocoder({
				city: "010", //城市设为北京,默认:“全国”
				radius: 1000 //范围,默认:500
			})
			geocoder.getAddress(center, function(status, result) {
				if (status === 'complete' && result.regeocode) {
					success(result)
				} else{
					fail(result)
				}
			})
		}
		/**
		 * 地址=>坐标
		 * params: {address: '地址', success: '成功回调', fail: '失败回调'}
		 */
		this.parseAddress = (address, success, fail) => {
			var geocoder = new AMap.Geocoder({
				// city: "010", //城市设为北京,默认:“全国”
			})
			geocoder.getLocation(address, function(status, result) {
				if (status === 'complete' && result.geocodes.length) {
					// var lnglat = result.geocodes[0].location
					success(result)
				} else{
					fail(result)
					// log.error('根据地址查询位置失败')
				}
			})
		}
		/**
		 * 自定义信息窗体
		 * params: {lnglats: 坐标数组, success: '成功回调', fail: '失败回调'}
		 */
		this.renderInfoWindow = (lnglats) => {
			let map = this.newMap()
			var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)})
			for (var i = 0, marker; i < lnglats.length; i++) {
				var marker = new AMap.Marker({
					position: lnglats[i],
					map: map
				})
				marker.content = '我是第' + (i + 1) + '个Marker'
				marker.on('click', markerClick)
				marker.emit('click', {target: marker})
			}
			function markerClick(e) {
				infoWindow.setContent(e.target.content)
				infoWindow.open(map, e.target.getPosition())
			}
			map.setFitView()
		}
		/**
		 * 自定义marker
		 * params: {lnglats: 坐标数组, type: 'clockPoint或luckyBall', contentArr: 'marker内容'}
		 */
		this.modifyMarker = (center, lnglats, type = 'clockPoint', contentArr, success) => {
			let map = this.newMap(center)
			let markers = []
			let index = 0
			for (let i = 0; i < lnglats.length; i++) {
				let marker =  new AMap.Marker({
					position: lnglats[i],
					content: contentArr[i],
					// 以 icon 的 [center bottom] 为原点
					offset: new AMap.Pixel(-13, -30)
				})
				// 如果type是缘分球
				if (type === 'luckyBall') {
					if (i < lnglats.length - 1) {
						marker.on('click', function () {
							// 导航时传出当前坐标
							success(lnglats[i], 'pathTrans')
						})					
					}
				} else { // 如果type是打卡点
					if (i < lnglats.length - 1) {
						marker.on('click', function () {
							success(lnglats[i], 'detail')
						})					
					}
					if (i === lnglats.length - 1) {
						marker.on('click', function () {
							// 导航时传出当前坐标
							success(lnglats[i - 1], 'pathTrans')
						})					
					}					
				}
				markers.push(marker)
			}
			map.add(markers)
			map.setFitView()
		}
		/**
		 * 自定义路径导航
		 * params: {lnglats: 坐标数组, content: 'marker内容'}
		 */
		this.modifyPathTo = (center, startLngLat, endLngLat, success, fail) => {
			var map = this.newMap(center)
			var drivingOption = {
				policy: AMap.DrivingPolicy.LEAST_TIME, // 其它policy参数请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingPolicy
				ferry: 1, // 是否可以使用轮渡
				// province: '京', // 车牌省份的汉字缩写  
			}
			// 构造路线导航类
			var driving = new AMap.Driving(drivingOption)
			// 根据起终点经纬度规划驾车导航路线
			driving.search(new AMap.LngLat(startLngLat[0], startLngLat[1]), new AMap.LngLat(endLngLat[0], endLngLat[1]), function(status, result, map) {
				// result即是对应的驾车导航信息,相关数据结构文档请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
				if (status === 'complete') {
					if (result.routes && result.routes.length) {
						// 绘制第一条路线,也可以按需求绘制其它几条路线
						success(result.routes[0], map)
					}
				} else {
					fail(result)
				}
			})
		}
		/**
		 * 自定义窗体锚点
		 * params: {map: '当前map对象', center: '中心坐标', anchor: '展示位置:', content: '展示内容'}
		 * anchor: 左上'top-left'; 上中'top-center'; 右上'top-right'; 左中'middle-left'; 中'center'; 右中'middle-right'; 左下'bottom-left'; 下中'bottom-center'; 右下'bottom-right';
		 */
		this.modifyWindowMsg = (map, center, anchor, content) => {
			// let map = this.newMap(center)
			let infoWindow = new AMap.InfoWindow({
        anchor: anchor,
        content: content
			})
			infoWindow.open(map, center)
		}
	}
}

let amap = new AMAP()
export { amap }

amap 挂在 util 对象下,方便调用

import { amap } from './amap.js'

module.exports = {
  amap: amap
}

参考

Last updated