> 文章列表 > vue 高德地图 —— 点标记、信息弹窗、网页导航、获取经纬度及当前城市信息

vue 高德地图 —— 点标记、信息弹窗、网页导航、获取经纬度及当前城市信息

vue 高德地图 —— 点标记、信息弹窗、网页导航、获取经纬度及当前城市信息

新建 components/amap.vue 文件,封装高德地图组件:

<template><div><div id="amapcontainer" style="width: 800px; height: 520px"></div></div>
</template>
<script>
import AMapLoader from '@amap/amap-jsapi-loader';
window._AMapSecurityConfig = {securityJsCode: '' // '「申请的安全密钥」',
}
export default {name: "purchannel",data () {return {zoom: 12,originX: '',// 当前浏览器定位的位置originY: '',map: null, //地图实例infoWindow: '',makerList: [],provinceArr: [],cityArr: [],provinceCode: '',cityCode: '',storeList: [], //门店列表}},watch: { },created () { },mounted () { // DOM初始化完成进行地图初始化this.initAMap()},methods: {initAMap () {AMapLoader.load({key: "", // 申请好的Web端开发者Key,首次调用 load 时必填version: "2.0", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15plugins: ["AMap.Scale", "AMap.ToolBar", "AMap.ControlBar", 'AMap.Geocoder', 'AMap.Marker','AMap.CitySearch', 'AMap.Geolocation', 'AMap.AutoComplete', 'AMap.InfoWindow'], // 需要使用的的插件列表,如比例尺'AMap.Scale'等}).then((AMap) => {// 获取到作为地图容器的DOM元素,创建地图实例this.map = new AMap.Map("amapcontainer", { //设置地图容器idresizeEnable: true,zoom: this.zoom, // 地图显示的缩放级别viewMode: "3D", // 使用3D视图zoomEnable: true, // 地图是否可缩放,默认值为truedragEnable: true, // 地图是否可通过鼠标拖拽平移,默认为truedoubleClickZoom: true, // 地图是否可通过双击鼠标放大地图,默认为true// center: [113.370824, 23.131265], // 中心点坐标  广州// mapStyle: "amap://styles/darkblue", // 设置颜色底层});this.getLocation()this.setupMapTool()this.searchCityInfo()// 地图点击事件,点击获取经纬度;this.map.on("click", (e) => {// 获取经纬度// console.log('map click', e, e.lnglat.getLng(), e.lnglat.getLat());this.infoWindow.close()})}).catch(e => {console.log(e);})},setupMapTool () {// 添加工具条控件,工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件let controlBar = new AMap.ControlBar({position: {top: '10px',left: '10px',},});let toolBar = new AMap.ToolBar({position: {top: '110px',left: '35px'}});this.map.addControl(controlBar); // 方向盘this.map.addControl(toolBar);   // 添加右下角的放大缩小this.map.setDefaultCursor("pointer"); // 使用CSS默认样式定义地图上的鼠标样式},searchCityInfo () {// 获取当前城市,省份,经纬度范围const citySearch = new AMap.CitySearch()citySearch.getLocalCity((status, result) => {// console.log('citySearch', status, result);if (status === 'complete' && result.info === 'OK') {// 查询成功,result即为当前所在城市信息this.getDivision(0, 1, result.province, result.city)} else {console.log('CitySearch出错')}})},// 从高德地图api获取浏览器定位getLocation () {let geolocation = new AMap.Geolocation({// 是否使用高精度定位,默认:trueenableHighAccuracy: true,// 设置定位超时时间,默认:无穷大timeout: 10000,//  定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:falsezoomToAccuracy: true,panToLocation: true,     //定位成功后将定位到的位置作为地图中心点,默认:trueshowButton: true,        //显示定位按钮,默认:truebuttonPosition: 'LB',    //定位按钮停靠位置,默认:'LB',左下角buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)})geolocation.getCurrentPosition((status, result) => {// console.log('getCurrentPosition', status, result)if (status == 'complete') {// result是具体的定位信息this.originX = result.position.latthis.originY = result.position.lng} else {console.log('定位出错', result);}})},// 增加点标记setMapMarker () {// 创建 AMap.Icon 实例let icon = new AMap.Icon({size: new AMap.Size(36, 36), // 图标尺寸image: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png", // Icon的图像imageSize: new AMap.Size(24, 30), // 根据所设置的大小拉伸或压缩图片imageOffset: new AMap.Pixel(0, 0)  // 图像相对展示区域的偏移量,适于雪碧图等});//信息窗口实例this.infoWindow = new AMap.InfoWindow({anchor: "top-left",offset: new AMap.Pixel(0, -30)});let makerList = []this.storeList.forEach((item) => {// 遍历生成多个标记点let marker = new AMap.Marker({map: this.map,zIndex: 9999999,icon: icon, // 添加 Icon 实例offset: new AMap.Pixel(-13, -30), //icon中心点的偏移量position: [item.locationX, item.locationY] // 经纬度对象new AMap.LngLat(x, y),也可以是经纬度构成的一维数组[116.39, 39.9]});let content ='<ul style="  margin:-10px 0 5px 0; padding:0.2em 0;">'+ '<li style="line-height:26px; font-size:14px;color:#727272;margin-bottom:6px">'+ item.name + '</li>'+ '<li style="font-size:14px;color:#727272;">'+ '<span style="width:50px; display:inline-block;" >地 址:</span>'+ item.address + '</li>'+ '<li  style="font-size:14px;color:#727272;">'+ '<span style="width:50px; display:inline-block;">电 话:</span>'+ item.phone + '</li>'+ '</ul>'marker.content = contentmarker.on("click", this.markerClick)// marker.emit('click', { target: marker });// 此处是设置默认出现信息窗体makerList.push(marker)});this.makerList = makerListthis.map.add(makerList)// 自动适应显示想显示的范围区域this.map.setFitView();},// 控制标记的信息窗体的显示markerClick (e) {// 标注的点击事件this.infoWindow.setContent(e.target.content);this.infoWindow.open(this.map, e.target.getPosition());},// 开始定位beginLocate (x, y, index) {// console.log('x,y,this.makerList[index].content', this.makerList[index], x, y)this.map.panTo([x, y]) //设置地图中心点if (this.makerList[index]) {this.infoWindow.setContent(this.makerList[index].content)}this.infoWindow.open(this.map, [x, y])},// 地图导航beginNav (address, y, x) {let trimAdd = address.replace(/\\s+/g, "");let src = `https://uri.amap.com/navigation?from=${this.originY},${this.originX},当前位置&to=${y},${x},${trimAdd}&policy=1&coordinate=gaode&callnative=0`window.open(src)},/* @param code 编码* @param layer 层级 默认1级(省份)* @param province 默认地址 省份* @param city 默认地址  城市* 查询行政区域*/getDivision (code = 0, layer = 1, province, city) {let data = {parentCode: code};this.$http({method: 'GET',url: this.baseURI + "dictionary/queryDivision.json",params: data}).then(res => {  //接口返回数据if (res.data.mobBaseRes.code == 100) {if (layer == 1) {this.provinceArr = res.data.mobBaseRes.result;if (province) {this.provinceArr.forEach((value, index, arr) => {if (arr[index].name == province) {this.provinceCode = arr[index].code;this.getDivision(this.provinceCode, 2, province, city)}})}} else {this.cityArr = res.data.mobBaseRes.result;if (city) {this.cityArr.forEach((value, index, arr) => {if (arr[index].name == city) {this.cityCode = arr[index].code;this.querychannel(this.cityCode)}})}}} }).catch(err => {     })},/* @param id 渠道id* 查询指定行政区域的 marker 定位信息*/querychannel (id) {let data = {'divisionCode': id};this.$http({method: 'GET',url: this.baseURI + "services/channel/info/list.json",params: data}).then(res => {  //接口返回数据if (res.data.mobBaseRes.code == 100) {this.storeList = res.data.mobBaseRes.datas || []if (this.storeList.length) {this.setMapMarker()} else {this.removeMarker()}} }).catch(err => {})},// 清除点removeMarker () {if (this.makerList) {// 移除已创建的 markerthis.map.clearMap() // 清除所有覆盖物(点标志)this.makerList = []}}}
}</script><style lang="less" scoped>
</style>

接下来,在需要使用的组件中引入 amap.vue

<template><div><map-container></map-container></div>
</template>
<script>
import MapContainer from "@/components/amap";
export default {name: "purchannel",components: { MapContainer },data () {return { }},watch: {},created () { },mounted () { },methods: {}
}
</script><style lang="less" scoped>
</style>