如何在openlayers3中指定GeoJSON的投影? [英] How to specify the projection for GeoJSON in openlayers3?

查看:837
本文介绍了如何在openlayers3中指定GeoJSON的投影?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目的是加载GeoJSON数据并将其显示在地图上。 GeoJSON中指定的要素的坐标是正常的lon / lat。由于某些原因,openlayers使用地图使用的投影渲染它们而不转换它们。

My intention is to load GeoJSON data and display it on the map. Coordinates of the features specified in GeoJSON are normal lon/lat. For some reason openlayers is rendering them using the projection used by the map and without converting them.

// 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
    })
});

该点正在地图中间呈现。通过放置多个点我确定它们实际上相对于彼此移动但是少量使我相信由于某种原因地图使用不同的坐标系。

The point is being rendered in the middle of the map. By placing multiple points I determined that they are in fact moved relative to each other but by a small amount which leads me to believe the for some reason the map uses a different coordinate system for them.

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

What I tried: Setting crs in GeoJSON, providing defaultDataProjection option to format. I use openlayers v3.8.2 and all solutions I found online are very outdated (and as far as I can see the API used to be way better, maybe I should just switch to an old version).

推荐答案

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

Just use a featureProjection to read features like:

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

更新
从网址阅读功能更加轻松,OL在内部为您进行转换:

UPDATE: When reading features from url is even easier, OL makes the conversion internally for you:

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

这篇关于如何在openlayers3中指定GeoJSON的投影?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆