1、封装的高德地图
<template>
<!-- 动态绑定id,区分防多次调用的冲突!!! -->
<div :id="mapid" class="container"></div>
</template>
<style>
.container {
height: 263px;
width: 820px;
}
.custom-content-marker {
position: relative;
width: 25px;
height: 34px;
}
.custom-content-marker img {
width: 100%;
height: 100%;
/* border: 1px solid red; */
}
</style>
<script>
export default {
// 接受父组件传进来的id值,以及坐标值(数组:【X,Y】,mapid是动态id的值,slocalIp是传进的IP的值)
props: ["mapid", "slocalIp", "smapaddress"],
data: function () {
return {
map: null,
marker: null
};
},
created: function () {
},
mounted: function () {
// 创建地图实例
this.initMapInstance();
this.addressToMark(this.smapaddress); //后期传入地址!!!!!!smapaddress
if (this.slocalIp) {
this.addMark(this.slocalIp);
}
},
computed: {},
watch: {
slocalIp(val) {
if (val) {
this.addMark(val);
}
},
smapaddress(val) {
if (val) {
this.addressToMark(val)
}
}
},
beforeDestroy: function () {
},
methods: {
initMapInstance() {
var position = new AMap.LngLat(121, 31);
this.map = new AMap.Map(this.mapid, {
zoom: 13,
center: position,
resizeEnable: true //是否监控地图容器尺寸变化,默认false
});
},
addressToMark(smapaddress) {
//地址转经纬度
if (smapaddress && smapaddress.length != 0) {
this.geoCode(smapaddress);
}
},
geoCode(address) {
let _this = this;
var geocoder = new AMap.Geocoder({
// city: "010" //城市设为北京,默认:“全国”
});
geocoder.getLocation(address, function (status, result) {
if (status === "complete" && result.info=="OK") {
var lnglat = result.geocodes[0].location; //经纬度的赋值
var localIp = [];
localIp.push(lnglat.R);
localIp.push(lnglat.Q);
_this.$emit("getIp",localIp);
_this.addMark(localIp);
} else {
// log.error("根据地址查询位置失败");
}
});
},
addMark(slocalIp) {
var _this = this;
var content = "<div class='custom-content-marker'><img src='//a.amap.com/jsapi_demos/static/demo-center/icons/dir-via-marker.png'></div>";
var position = new AMap.LngLat(slocalIp[0], slocalIp[1]);
if (!this.marker) {
_this.marker = new AMap.Marker({
position: position,
// 将 html 传给 content// 点标记显示内容,HTML要素字符串
content:content,
// 以 icon 的 [center bottom] 为原点
offset: new AMap.Pixel(-13, -30)
});
// 将 markers 添加到地图
_this.map.add(_this.marker);
} else {
_this.marker.setPosition(position);
}
this.map.setCenter(position);
},
},
components: {},
filters: {}
};
</script>
2、使用时,某个功能点
<EFMAP :mapid="mapid" :smapaddress="mapaddress" :slocalIp="ip" @getIp="onGetIp"></EFMAP>
methods:{
onGetIp(data){
console.log("子组件传过来的ip是",data);
this.ip = data;
},
},
components: {
EFMAP: resolve => require(['@/components/map'], resolve)
},