javascript - 显示带有 openlayers 和外部 geojson 文件的简单图标

标签 javascript openlayers geojson

我需要一些帮助,我下面有这段代码,它正在工作,但我想将 de“geojsonObject”不是放在变量中,而是放在 .geojson 文件中并加载它,我不太熟悉使用 javascript 和 geojson。

import 'ol/ol.css';
import Feature from 'ol/Feature';
import Map from 'ol/Map';
import View from 'ol/View';
import GeoJSON from 'ol/format/GeoJSON';
import Circle from 'ol/geom/Circle';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
import {OSM, Vector as VectorSource} from 'ol/source';
import {Circle as CircleStyle, Fill, Stroke, Style} from 'ol/style';
import {Icon} from 'ol/style';

var image = new CircleStyle({
  radius: 5,
  fill: null,
  stroke: new Stroke({color: 'red', width: 1})
});

var styles = {
  'Point': new Style({
               image: new Icon({
        rotation: 180 / 180 * 3.14,
                src: 'data/test.svg'
               })
    })
};

var geojsonObject = {
  'type': 'FeatureCollection',
  'crs': {
    'type': 'name',
    'properties': {
  'name': 'EPSG:3857'
    }
  },
  'features': [{
    'type': 'Feature',
    'rotation': 180 / 180 * 3.14,
    'geometry': {
      'type': 'Point',
      'coordinates': [0, 0]
    }
  }]
};

var styleFunction = function(feature) {
  return styles[feature.getGeometry().getType()];
};

var vectorSource = new VectorSource({
  features: (new GeoJSON()).readFeatures(geojsonObject)
});

vectorSource.addFeature(new Feature(new Circle([5e6, 7e6], 1e6)));

var vectorLayer = new VectorLayer({
  source: vectorSource,
  style: styleFunction
});

var map = new Map({
  layers: [
    new TileLayer({
      source: new OSM()
    }),
    vectorLayer
  ],
  target: 'map',
  view: new View({
    center: [0, 0],
    zoom: 2
  })
});

我尝试使用下面的 test.geojson 文件,但我不知道它是否正确,而且我想知道如何更改“vectorSource”来加载它

{
  "type": "FeatureCollection",
  "crs": {
    "type": "name",
    "properties": {
      "name": "EPSG:3857"
    }
  },
  "features": [{
    "type": "Feature",
    "rotation": 90 / 180 * 3.14,
    "geometry": {
      "type": "Point",
      "coordinates": [0, 0]
    }
  }]
}

最佳答案

OpenLayers 将加载并解析 URL

var vectorSource = new VectorSource({
  format: new GeoJSON(),
  url: 'test.geojson'
});

如果您使用文件扩展名 .geojson,请确保在您的服务器 MIME 类型中启用它(否则只需使用 .json)

如果您想从 geojson 访问非标准属性,它们必须进入属性对象

  "features": [{
    "type": "Feature",
    "properties" : {
      "rotation": 90 / 180 * 3.14
    },
    "geometry": {
      "type": "Point",
      "coordinates": [0, 0]
    }
  }]

关于javascript - 显示带有 openlayers 和外部 geojson 文件的简单图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58242832/

相关文章:

javascript - 获取 Backbone 集合中属性不等于某个值的所有模型

javascript - 在 Chart.js 2 中修改散点图的 X 轴标签

z-index - 更改 openlayers 中标记的 z 索引

python - 无法在虚拟主机 apache 上执行 proxy.cgi

javascript - 传单和 GeoJSON

javascript - 执行正则表达式,同时将所有变量保留在 block 范围内

javascript - 为什么我的自定义 Promise 的等待调用挂起?

javascript - Openlayers - 禁用图层上的平移

java - Junit 测试断言错误预期为 3,但结果为 0

javascript - 传单 - 寻找将 onEachFeature 添加到现有 geojson 层的方法