父组件使用
<location :location='location' :locationSize='locationSize'/>
import Location from '@/components/location'
export default{
components:['Location']
data() {
return {
location:[15.11,22.11], //位置坐标
locationSize:'width:100%;height:200px', //地图大小显示设置
};
},
}
地图组件封装
<template>
<div>
<div id="map-location" :style="locationSize">
</div>
</div>
</template>
<script>
var map, marker;
export default {
props:['locationSize','location'], //接收父组件传来的位置坐标和样式
data() {
return {
arriveCoor: this.location, //坐标点
arrive: "", //位置信息
};
},
mounted() {
this.mapDraw(this.arriveCoor)
this.mapCoor(this.arriveCoor);
},
methods: {
mapDraw(arriveCoor) {
map = new AMap.Map("map-location", {
//map-location是嵌地图div的id
resizeEnable: true, //是否监控地图容器尺寸变化
zoom: 16, //初始化地图层级
center: arriveCoor, //初始化地图中心点
});
// 定位点
this.addMarker(arriveCoor);
},
// 实例化点标记
addMarker(arriveCoor) {
var _this = this;
marker = new AMap.Marker({
icon: "",
imageSize: "20px",
position: arriveCoor,
offset: new AMap.Pixel(-13, -30),
// 设置是否可以拖拽
draggable: true,
cursor: "move",
// 设置拖拽效果
raiseOnDrag: true,
});
marker.setMap(map);
}, // 查询坐标
mapCoor(lnglatXY) {
var _this = this;
AMap.service("AMap.Geocoder", function () {
var geocoder = new AMap.Geocoder({});
geocoder.getAddress(lnglatXY, function (status, result) {
if (status === "complete" && result.info === "OK") {
_this.arrive = result.regeocode.formattedAddress;
} else {
_this.arrive = "暂无位置";
}
});
});
},
},
};
</script>
效果图: