【问题标题】:How to specify the projection for GeoJSON in openlayers3?如何在 openlayers3 中指定 GeoJSON 的投影?
【发布时间】:2015-09-08 10:12:41
【问题描述】:

我的目的是加载 GeoJSON 数据并将其显示在地图上。 GeoJSON 中指定的特征坐标是正常的经度/纬度。出于某种原因,openlayers 使用地图使用的投影来渲染它们,而不是转换它们。

// Underlying sat layer.
var world = new ol.layer.Tile({
    source: new ol.source.MapQuest({layer: 'sat'})
});

// GeoJSON data.
var geojsonObject = {
    'type': 'FeatureCollection',
    'features': [
        {
            'type': 'Feature',
            'geometry': {
                'coordinates': [ 50.07539747, 19.76809501 ], 
                'type': 'Point'
            },
        }
    ]
};

var vectorSource = new ol.source.Vector({
    features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
});

var vectorLayer = new ol.layer.Vector({
    source: vectorSource
});

// Map.
map = new ol.Map({
    target: 'map',
    layers: [world, vectorLayer],
    view: new ol.View({
        center: ol.proj.transform([37.41, 8.82], 'EPSG:4326', 'EPSG:3857'),
        zoom: 2
    })
});

该点正在地图中间进行渲染。通过放置多个点,我确定它们实际上是相对于彼此移动的,但移动量很小,这让我相信由于某种原因,地图为它们使用了不同的坐标系。

我尝试了什么: 在 GeoJSON 中设置crs,提供defaultDataProjection 选项来格式化。我使用 openlayers v3.8.2,我在网上找到的所有解决方案都非常过时(据我所知,API 曾经更好,也许我应该切换到旧版本)。

【问题讨论】:

    标签: javascript openlayers-3


    【解决方案1】:

    只需使用featureProjection 即可阅读以下功能:

    var vectorSource = new ol.source.Vector({
        features: new ol.format.GeoJSON().readFeatures(geojsonObject,{
            featureProjection: 'EPSG:3857'
        })
    });
    

    更新: 当从 url 读取特征变得更加容易时,OL 会在内部为您进行转换:

    var geojson_layer = new ol.layer.Vector({
        source: new ol.source.Vector({
            url: 'file.geojson',
            format: new ol.format.GeoJSON()
        })
    });
    

    演示 - http://plnkr.co/edit/GvdVNE?p=preview

    【讨论】:

    • 这有点帮助 - 点移动并且现在更加分散,但它们仍然与背景中卫星地图上的位置不匹配。此外,在使用url 参数加载时,此方法也不起作用,我假设我必须自己下载数据并且不能只在源中设置投影?
    • 我会接受这个答案,因为它可能是正确的,而我是那个有问题的人。无论如何,我将切换到另一个库或自己编写一些东西,因为尽管它是 3.8.2 版本,但它似乎记录不充分且半成品。
    • 谢谢,您的回答帮助我从 GeoJSON 数据中绘制形状。
    • 在此答案中使用第一个版本时,应将 dataProjection 与 featureProject 一起提供。见this answer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    相关资源
    最近更新 更多