Wednesday, 6 January 2016

OpenLayers 4 does not display vector layer from geoJSON



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:




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?



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


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...