我正在尝试导出功能,然后将它们加载到映射我已经可以保存功能并通过Geojson对象重新创建它们。
问题是GeoJson不保存功能的样式。
保存样式和加载特性的最好方法是什么?
你可以使用下面的代码来保存和加载geojson文件的样式。
在标题
中添加以下行<script src=" https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js"></script> <!-- we will use it to download the geojson file -->
然后在代码中添加以下函数:
function saveMap() {
var mapLayers = map.getLayers().getArray();
var features = [];
mapLayers.forEach(function(layer) {
if (layer instanceof ol.layer.Vector) {
var layerFeatures = layer.getSource().getFeatures();
layerFeatures.forEach(function(feature) {
feature.setProperties(layer.getStyle()) //add the layer styles to the feature as properties
features.push(feature);
});
}
});
var geojsonFormat = new ol.format.GeoJSON();
var geojsonString = geojsonFormat.writeFeatures(features, {
featureProjection: map.getView().getProjection()
});
var blob = new Blob([geojsonString], {
type: 'text/plain'
});
saveAs(blob, 'map.geojson');
}
用OpenLayers中的样式重新加载地图:
// Use jQuery to read the GeoJSON file
$.getJSON("map.geojson", function(data) {
var geojson = new ol.format.GeoJSON({
dataProjection: "EPSG:4326",
featureProjection: 'EPSG:3857'
}).readFeatures(data);
var vectorSource = new ol.source.Vector({
features: geojson,
wrapX: false
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
})
// Iterate through the features in a vector layer
vectorLayer.getSource().forEachFeature(function(feature) {
// Take the style of the feature as a variable
var fill_color = feature.values_[0].fill_.color_;
var stroke_color = feature.values_[0].stroke_.color_;
var stroke_width = feature.values_[0].stroke_.width_;
// Create a style object
var style = new ol.style.Style({
stroke: new ol.style.Stroke({
color: stroke_color,
width: stroke_width
}),
fill: new ol.style.Fill({
color: fill_color
})
});
// Add the style to the feature
feature.setStyle(style);
});
map.addLayer(vectorLayer);
});
您可以查看以下链接的完整代码
ol-save-geojson.html
ol-read-geojson-styles.html