我正在从OpenLayers 3.2.0迁移到3.5.0,并且无法将GeoJSON数据加载到矢量层中。我可以使用它,但是在将它们添加到矢量源之前,我正在从GeoJSON数据源转换要素的几何形状。

有没有办法让OpenLayers 3.5. 0 auto 应用转换?

我的GeoJSON数据源中的数据使用了EPSG:4326,我相信我需要将这些几何图形重新投影到EPSG:3857才能在我的 map 上显示它们。 GeoJSON数据源的crs属性具有投影信息,而我的矢量源也具有其投影集。尽管如此,要素几何并不会自行转换。

我需要通过URL将可见 map 区域的边界传递给我的GeoJSON数据源,我不想一次加载所有数据。我的向量源上有一个加载器函数,该函数获取当前 map 范围并构建请求的URL。

Sample Data from my GeoJSON源可用,它可以通过短绒棉纸进行验证,我认为这是合理的。

下面是我正在使用的当前代码。

var vectorFormat = new ol.format.GeoJSON();
var featureStyle = new ol.style.Style({
    image: new ol.style.Circle({
      radius: 5,
    fill: new ol.style.Fill(
      {color: 'rgba(255, 69, 0, 0.75)'}),
    stroke: new ol.style.Stroke(
      {color: 'rgba(255, 0, 0, 0.95)', width: 1})
    })
 });

var vectorSource = new ol.source.Vector({
    projection: new ol.proj.Projection({'code':'EPSG:3857'}),
    strategy: ol.loadingstrategy.bbox,
    loader: function(extent, resolution, projection) {
      var coordinate1 = ol.proj.transform([extent[0], extent[1]],
        'ESPG:3857', 'EPSG:4326')
      var coordinate2 = ol.proj.transform([extent[2], extent[3]],
        'ESPG:3857', 'EPSG:4326')
      var url = 'api/sites/geo/bounds/4326/' + coordinate1[1]
        + ',' + coordinate1[0] + '/' + coordinate2[1] + ','
        + coordinate2[0] + "/";
        $.ajax({
            url: url,
            dataType: 'json'
        }).then(function(response) {
            var features = vectorFormat.readFeatures(response);
            var transformFn = ol.proj.getTransform(
              response.crs.properties.name, projection);
            for(index in features) {
                var feature = features[index];
                feature.getGeometry().applyTransform(transformFn);
            }
            vectorSource.addFeatures(features);
        });
    }
});

this.state.map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      }),
      new ol.layer.Vector({
        source: vectorSource,
          style: featureStyle
        })
     ],
     view: new ol.View({
        center: this.transformToOl(this.state.center),
        zoom: this.state.zoom
      })
});

任何对正确方向的帮助或指导,将不胜感激。 :-D

最佳答案

是的,OpenLayers可以为您进行重新投影。您甚至不必在源上设置投影。几何形状将自动重新投影到 View 投影。

var vectorSource = new ol.source.Vector({
  url: 'file.json',
  format: new ol.format.GeoJSON()
});

http://jsfiddle.net/h9zwjf88/

更新

如果要使用自定义加载器,则可以在解析功能时指定目标投影(另请参见ol.format.GeoJSON.html#readFeatures):
var vectorSource = new ol.source.Vector({
  strategy: ol.loadingstrategy.bbox,
  loader: function(extent, resolution, projection) {
    $.ajax(url).then(function(response) {
      var features = format.readFeatures(response,
        {featureProjection: 'EPSG:3857'});
      vectorSource.addFeatures(features);
    });
  }
});

http://jsfiddle.net/h9zwjf88/1/

关于geojson - 如何基于 map 范围将GeoJSON数据动态加载到OpenLayers 3.5.0 map 图层中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30510249/

10-09 15:26
查看更多