OpenLayers – Resolving Issue with Vector Layer Not Displaying from geoJSON

geojsonopenlayersvector-layer

I am using OpenLayers 4.0.1 and here is my json in pastebin, because it is too large for embedded code: http://pastebin.com/VfLn0RR0
Projection of vector data is 4326 LineString.

html code:

<div id="map" class="map"></div>

and here is my JS code for OpenLayers:

var routeJSON = {...}; // json which I uploaded on pastebin

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

var vectorLayer = new ol.layer.Vector({
    source: vectorSource,
    style: new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: 'red',
            width: 3
        })
    })
});

var map = new ol.Map({
    target: 'map',
    layers: [
        vectorLayer,
        new ol.layer.Tile({
            source: new ol.source.OSM()
        }),
        vectorLayer
    ],
    view: new ol.View({
        center: ol.proj.fromLonLat([22.00, 48.82]),
        zoom: 10
    })
});

Base map is displayed OK, on it I want fill my route from geojson.

Can you tell me where I have a mistake?

Best Answer

Your map is projected in EPSG:3857 while your data is projected in EPSG:4326. You need to tell ol3 that your data should be reprojected to your map projection

To do so, just set featureProjection in your format declaration, like so:

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

Here is a fiddle to see it in action

Related Question