loadBoundaryMap() {
var textStyle = new Text({
font: "12px 微软雅黑",
fill: new Fill({
color: "#333",
}),
});
// 设置文本内容
textStyle.setText("");
var style = new Style({
stroke: new Stroke({
color: "#3d9e98",
width: 5,
}),
fill: new Fill({
color: "rgba(237, 243, 243, 0.3)" // 绿色的填充,rgba(237, 243, 243, 0.2) 表示绿色,第四个参数是透明度
}),
text: textStyle, // 将文本样式应用到图层样式中
});
const vectorSource = new VectorSource({
url: "data/hubei.json",
format: new GeoJSON(),
});
// 创建一个图层
this.vectorLayer = new VectorLayer({
zIndex: 0,
source: vectorSource,
});
// 将图层添加到地图中
this.map.addLayer(this.vectorLayer);
// 在加载完成后执行回调
vectorSource.once('change', () => {
if (vectorSource.getState() === 'ready') {
// 获取地图数据的范围
const dataExtent = vectorSource.getExtent();
//将样式应用到图层
this.vectorLayer.setStyle(style);
// 计算视图的中心
const center = getCenter(dataExtent);
// 设置视图的中心和缩放级别,以确保地图数据居中显示
this.map.getView().setCenter(center);
this.map.getView().fit(dataExtent, {
padding: [50, 50, 50, 50], // 可选的填充以确保地图数据不会紧贴地图边缘
});
}
});
},
只需要将代码放入地图相关代码中,然后调用 loadBoundaryMap()函数即可。但是需要注意的是,要将代码中的url路径改为自己需要加边框的json路径,对应的省份json数据格式可以到DataV.GeoAtlas地理小工具系列中去下载