通过url获取GeoJSON
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import GeoJSON from "ol/format/GeoJSON";
let url = getGeoserverHost() + '/geoserver/one/ows' +
'?service=WFS' +
'&version=1.0.0' +
'&request=GetFeature' +
'&typeName=' + typeName +
'&maxFeatures=5000000' +
'&outputFormat=application/json'
let vectorLayer = new VectorLayer({
name: code,
visible: false,
source: new VectorSource({
url: url,
format: new GeoJSON(),
resultFormat: 'json',
}),
style: getMyVectorLayerStyle(data.layer_code),
declutter: true, //重要的一行,确保label不重叠
})
加载本地GeoJSON数据(也是json格式数据)
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import GeoJSON from "ol/format/GeoJSON";
loadGeoJSON() {
const vectorSource = new VectorSource({
format: new GeoJSON(),
features: new GeoJSON().readFeatures(data),
})
this.vectorLayer = new VectorLayer({
source: vectorSource,
style: this.getStyleFunction(),
})
this.map.addLayer(this.vectorLayer)
}
getStyleFunction() {
return function (feature) {
const text = feature.get('name')
const style = new Style({
stroke: new Stroke({
color: 'blue',
width: 1.5,
}),
//填充色
fill: new Fill({
color: 'rgba(0, 0, 255, 0.15)',
}),
text: new Text({
textAlign: 'center', //位置
text: text,
// font: '14px bold serif',
font: '14px sans-serif',
padding: [2, 2, 2, 2],
fill: new Fill({
color: 'rgba(255, 255, 255, 1)', // 文本填充样式(即文字颜色)
}),
}),
})
return style
}
}
let json = await fetch(
"http://120.76.197.111:8090/geoserver/csdn_data/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=csdn_data%3Asichuan&maxFeatures=50&outputFormat=application%2Fjson"
).then((response) => {
return response.json();
});
this.features = new GeoJSON().readFeatures(json);