[英]OpenLayers export features with their styles
我正在尝试导出功能,然后将它们加载到 map 我已经可以保存功能并通过 Geojson object 重新创建它们。
问题是 GeoJson 不保存功能的样式。
保存 styles 并为其加载功能的最佳方法是什么?
您可以使用以下代码通过 styles 保存和加载 geojson 文件。
将以下行添加到 header
<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。
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 中用 styles 再次加载 map:
// 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);
});
您可以查看以下链接的完整代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.