1.pc端引入高德地图,然后再地图控件中加入事件,可能会导致地图组件无法渲染
解决方法,封装引入高德地图
1.在assets中新建AMap.js
export default function MapLoader () { // <-- 原作者这里使用的是module.exports
return new Promise((resolve, reject) => {
if (window.AMap) {
resolve(window.AMap)
} else {
var script = document.createElement('script')
script.type = 'text/javascript'
script.async = true
script.src = 'http://webapi.amap.com/maps?v=1.3&callback=initAMap&key=af8225fbf869e343c31df0e39430a940'
script.onerror = reject
document.head.appendChild(script)
}
window.initAMap = () => {
resolve(window.AMap)
}
})
}
用于动态引入高德地图API
2.在要是用的vue组件中引入
import MapLoader from “@/assets/js/AMap”
3.在mounted生命周期中初始化(我试过不能再created中初始化)
mounted() {
let that = this;
MapLoader().then(
(AMap) => {
console.log("地图加载成功");
that.map = new AMap.Map("container", {
center: [117.000923, 36.675807],
zoom: 11,
});
},
(e) => {
console.log("地图加载失败", e);
}
);
},
2.vue中引入高德地图的定位和关键字搜索功能
在index.html中写入
<script type="text/javascript"
src="https://webapi.amap.com/maps?v=1.4.15&key=af8225fbf869e343c31df0e39430a940&plugin=AMap.Autocomplete,AMap.PlaceSearch"></script>
然后再需要使用的组件中
html:
<template>
<div class="map-chart">
<div id="container" ref="container" />
<div id="myPageTop">
<table>
<tr>
<td>
<label>请输入关键字:</label>
</td>
</tr>
<tr>
<td>
<input id="tipinput">
</td>
</tr>
</table>
</div>
</div>
</template>
script:
export default {
name: 'Map',
props: [],
data() {
return {
placeSearch: null
}
},
mounted() {
this.mapInit()
},
methods: {
mapInit() {
const map = new AMap.Map(this.$refs.container, {
resizeEnable: true
}) // 创建Map实例
const options = {
'showButton': true, // 是否显示定位按钮
'buttonPosition': 'LB', // 定位按钮的位置
'buttonOffset': new AMap.Pixel(10, 20), // 定位按钮距离对应角落的距离
'showMarker': true, // 是否显示定位点
'showCircle': true, // 是否显示定位精度圈
'circleOptions': {// 定位精度圈的样式
'strokeColor': '#0093FF',
'noSelect': true,
'strokeOpacity': 0.5,
'strokeWeight': 1,
'fillColor': '#02B0FF',
'fillOpacity': 0.25
},
zoomToAccuracy: true // 定位成功后是否自动调整地图视野到定位点
}
AMap.plugin(["AMap.Geolocation"], function () {
const geolocation = new AMap.Geolocation(options);
map.addControl(geolocation);
geolocation.getCurrentPosition();
});
//注意:要在绑定事件前记录this,否则在绑定的回调方法中使用this将是该事件的this
const _this = this;
AMap.event.addListener(map, "click", function (e) {
map.clearMap(); // 清除地图上所有添加的覆盖物
new AMap.Marker({
position: e.lnglat,
map: map,
});
_this.handleMap(e.lnglat.getLng(), e.lnglat.getLat());
});
// 输入提示
const autoOptions = {
input: 'tipinput'
}
const auto = new AMap.Autocomplete(autoOptions)
this.placeSearch = new AMap.PlaceSearch({
map: map
}) // 构造地点查询类
AMap.event.addListener(auto, 'select', this.select)// 注册监听,当选中某条记录时会触发
//点击搜索出的mark点事件
AMap.event.addListener(this.placeSearch, 'markerClick', function(e) {
_this.$emit('bMapDate', e.data.location.lng, e.data.location.lat)
})
},
select(e) {
this.placeSearch.setCity(e.poi.adcode)
this.placeSearch.search(e.poi.name) // 关键字查询查询
},
handleMap(o, a) {
this.$emit('bMapDate', o, a)
}
}
}
</script>