Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

javascript - How to specify the projection for GeoJSON in openlayers3?

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.

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just use a featureProjection to read features like:

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...