首页 / OpenLayers / API 文档
GeoJSONFormat
先看结论
GeoJSON 解析器。在 JSON 文本与要素之间来回转换,读取时可按目标投影自动换算坐标。
new ol.format.GeoJSON(options)
构造参数
| 参数 | 说明 |
|---|---|
dataProjection | 数据本身的投影,默认 'EPSG:4326' |
featureProjection | 读出与写出时的目标投影,省略则不换算 |
geometryName | 写出时几何体使用的属性名,默认 'geometry' |
extractGeometryName | 读取时是否按几何属性名识别,默认 false |
常用方法
| 方法 | 返回 | 说明 |
|---|---|---|
readFeatures(source, options) | Array<Feature> | 读 FeatureCollection 或单个要素,返回数组 |
readFeature(source, options) | Feature | 读单个要素,传入集合时取第一个 |
readGeometry(source, options) | Geometry | 只读几何部分 |
writeFeatures(features, options) | string | 要素数组序列化为 JSON 文本 |
writeFeaturesObject(features, options) | Object | 要素数组序列化为可继续加工的对象 |
writeGeometry(geometry, options) | string | 几何体序列化为 JSON 文本 |
var format = new ol.format.GeoJSON({ featureProjection: 'EPSG:3857' });
var features = format.readFeatures({
type: 'FeatureCollection',
features: [{
type: 'Feature',
properties: { name: '监测点 A', level: 3 },
geometry: { type: 'Point', coordinates: [116.391263, 39.907359] }
}]
});
console.log(features[0].getGeometry().getCoordinates()); // 米制坐标
var text = format.writeFeatures(features, {
featureProjection: 'EPSG:3857',
dataProjection: 'EPSG:4326'
});
console.log(text.slice(0, 60));
注意事项
- 省略
featureProjection时坐标原样保留,直接读进 3857 视图会偏移到几百万米外。 readFeatures始终返回数组,即使输入是单个 Feature;需要单要素时用readFeature。- 写出时
featureProjection与dataProjection都建议显式给出,依赖默认值容易在切换视图后输出错误坐标。 - 写出时要素
id落在 GeoJSON 顶层id字段,业务属性仍在properties中,读取时不要期望在属性里取到它。
经纬志(2026)。《GeoJSONFormat》。https://www.jingweizhi.com/openlayers/api/geojson-format.html(访问日期 2026-11-03)。