使用OpenLayers的format类中的GeoJSON类将GeoJSON数据转换为Feature对象。示例代码如下:
var geoJsonData = { // GeoJSON数据
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [125.6, 10.1]
},
"properties": {
"name": "Point A"
}
},
{
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
[125.6, 10.1],
[125.7, 10.2],
[125.8, 10.3]
]
},
"properties": {
"name": "LineString A"
}
}
]
};
var geoJsonFormat = new ol.format.GeoJSON(); // 创建GeoJSON格式化对象
var features = geoJsonFormat.readFeatures(geoJsonData); // 将GeoJSON数据转换为Feature对象
// 将Feature对象添加到矢量图层中
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({
features: features
})
});
// 添加矢量图层到地图中
var map = new ol.Map({
target: 'map',
layers: [vectorLayer],
view: new ol.View({
center: [125.6, 10.1],
zoom: 10
})
});
v2:
import GeoJSON from 'ol/format/GeoJSON';
const geoJSON = '{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[1,1]},"properties":{}},{"type":"Feature","geometry":{"type":"LineString","coordinates":[[2,2],[3,3],[4,4]]},"properties":{}}]}';
const format = new GeoJSON();
const features = format.readFeatures(geoJSON);
// 确保要素对象被正确识别
console.log(features);
writeFeatures()方法,可以将Feature对象转换为GeoJSON格式的数据
使用ol.format.WKT()
对象来将WKT格式的数据转换为ol.Feature
对象。
var wkt = 'POLYGON((10 10, 10 20, 20 20, 20 10, 10 10))';
var format = new ol.format.WKT();
var feature = format.readFeature(wkt);
var layer = new ol.layer.Vector({
source: new ol.source.Vector({
features: [feature]
})
});
var map = new ol.Map({
target: 'map',
layers: [layer],
view: new ol.View({
center: [0, 0],
zoom: 2
})
});