关于如何使用百度地图API这里就不多复述了,这里是工作中遇到的问题,简单的记录下,来直接上需求:
在百度地图中根据城市坐标呈现对应的柱状图信息。这里主要使用了百度提供的“覆盖物”接口来自定义图形
- 效果图
<template>
<div class="test">
<div id="allmap" style="width: 50%; height: 600px;"></div>
</div>
</template>
<script>
export default {
name: "test",
components: {},
data() {
return {
mp: null
};
},
mounted() {
this.initMap();
},
methods: {
// 初始化地图
initMap() {
this.mp = new BMap.Map("allmap");
this.mp.enableScrollWheelZoom();
this.drawArea("四川省");
this.drawBar();
},
// 画柱状图
drawBar() {
const _this = this;
// 创建bar的构造函数
function Bar(point, tips) {
this._point = point;
this._tips = tips;
}
// Bar类继承百度覆盖物类
Bar.prototype = new BMap.Overlay();
// 自定义覆盖物需重写以下两个方法
Bar.prototype.initialize = function(map) {
this._map = map;
var div = (this._div = document.createElement("div"));
div.style.position = "absolute";
div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat);
div.style.backgroundColor = "#EE5D5B";
div.style.color = "white";
div.style.height = "100px";
div.style.padding = "10px";
div.style.lineHeight = "18px";
div.style.whiteSpace = "nowrap";
div.style.MozUserSelect = "none";
div.style.fontSize = "16px";
var span = (this._span = document.createElement("span"));
span.style.position = "absolute";
span.style.top = "-20px";
span.style.left = "-5px";
span.style.color = "#000";
span.style.fontWeight = "bold";
div.appendChild(span);
span.appendChild(document.createTextNode(this._tips));
div.onmouseover = function() {
this.style.backgroundColor = "#6BADCA";
this.style.fontSize = "18px";
};
div.onmouseout = function() {
this.style.backgroundColor = "#EE5D5B";
this.style.fontSize = "16px";
};
_this.mp.getPanes().labelPane.appendChild(div);
return div;
};
Bar.prototype.draw = function() {
var map = this._map;
var pixel = map.pointToOverlayPixel(this._point);
this._div.style.left = pixel.x + "px";
this._div.style.top = pixel.y - 100 + "px"; // 这里y轴减去的是bar的高度
};
// 画柱状图 **此处可以优化**
var myBar1 = new Bar(
new BMap.Point(104.090763, 30.544933),
"成都:500人有钱"
);
_this.mp.addOverlay(myBar1);
var myBar2 = new Bar(
new BMap.Point(104.670278, 31.487738),
"绵阳:20人有钱"
);
_this.mp.addOverlay(myBar2);
},
// 确定行政区域
drawArea(name) {
const _this = this;
var bdary = new BMap.Boundary();
bdary.get(name, function(rs) {
//获取行政区域
//_this.mp.clearOverlays(); //清除地图覆盖物
var count = rs.boundaries.length; //行政区域的点有多少个
if (count === 0) {
alert("未能获取当前输入行政区域");
return;
}
var pointArray = [];
for (var i = 0; i < count; i++) {
var ply = new BMap.Polygon(rs.boundaries[i], {
strokeWeight: 2,
strokeColor: "blue"
}); //建立多边形覆盖物
_this.mp.addOverlay(ply); //添加覆盖物
pointArray = pointArray.concat(ply.getPath());
}
_this.mp.setViewport(pointArray); //调整视野
});
}
}
};
</script>
<style lang='scss' scoped>
</style>
- 未完待续
- 这里只是假数据呈现,如果真实的数据,根据数据动态的创建bar的高度,比如我这里定死了bar的高度是100px,那么需要计算下比如A点数据与B点数据的相比值是多少,分别占了100px的多少来动态构建。
- 创建bar的那里也可以重新的封装下,压进个队列最后循环去渲染。
- 在确定bar的top值的时候,最好初始top值需要减去一个当前bar的高度,这样的效果是最好的,以当前点向上创建了个bar。
- 其余的针对bar的事件操作就跟原来操作dom一样去完善就行了。