Skip to content

GeoJSON

GeoJSON 标准

用 GeoJSON 数据创建几何体

一份 GeoJSON 数据

data.json

json
{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "name": "点"
      },
      "geometry": {
        "coordinates": [90.46304141106367, 42.51092588497207],
        "type": "Point"
      },
      "id": 0
    },
    {
      "type": "Feature",
      "properties": {
        "name": "线段"
      },
      "geometry": {
        "coordinates": [
          [91.53970156731299, 44.15299130959545],
          [89.80386172356208, 43.34350165904692],
          [92.67129336418742, 42.53926440094088],
          [92.00112734856248, 43.447280553540224]
        ],
        "type": "LineString"
      },
      "id": 1
    },
    {
      "type": "Feature",
      "properties": {
        "name": "多边形"
      },
      "geometry": {
        "coordinates": [
          [
            [89.03481875481185, 42.092459364925986],
            [88.93594180168662, 40.97403450107839],
            [91.80337344231197, 41.18107729568305],
            [91.85830508293708, 42.07615215050859],
            [89.03481875481185, 42.092459364925986]
          ]
        ],
        "type": "Polygon"
      },
      "id": 2
    }
  ]
}
jsx
import "ol/ol.css";
import Map from "ol/Map.js";
import OSM from "ol/source/OSM.js";
import TileLayer from "ol/layer/Tile.js";
import View from "ol/View.js";
import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";
import GeoJSON from "ol/format/GeoJSON.js";
import { fromLonLat } from "ol/proj";
import data from "./data.json";

const map = new Map({
  target: "map",
  layers: [
    new TileLayer({
      source: new OSM(),
    }),
  ],
  view: new View({
    center: fromLonLat([90.46304141106367, 42.51092588497207]),
    zoom: 7,
  }),
});

const vectorSource = new VectorSource();
const vectorLayer = new VectorLayer({
  source: vectorSource,
});
map.addLayer(vectorLayer);

const features = new GeoJSON({
  dataProjection: "EPSG:4326", // geojson数据的坐标
  featureProjection: "EPSG:3857", // 转换为的Feature的坐标
}).readFeatures(data);

vectorSource.addFeatures(features);