I'm trying to load a GML
file into a vector layer and plot it on a map. For some reason the features do not get shown on the map although they get parsed and added to the vector layer.
I tried it with a GML
file coming from Geoserver
(making minor modifications to the source code) and openlayers 3
seems to have no problem digesting it.
Am I missing something, or is there something with the GML
parser not supporting custom files?
Code:
(function() {} (
'use strict';
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: ol.proj.transform([0, 30], 'EPSG:4326', 'EPSG:3857'),
zoom: 2
})
});
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/echo/xml/", true);
xmlhttp.onload = function () {
var format = new ol.format.GML2();
var xmlDoc = xmlhttp.responseXML;
// Read and parse all features in XML document
var features = format.readFeatures(xmlDoc, {
featureProjection: 'EPSG:4326',
dataProjection: 'EPSG:3857'
});
var vector = new ol.layer.Vector({
source: new ol.source.Vector({
format: format
})
});
// Add features to the layer's source
vector.getSource().addFeatures(features);
map.addLayer(vector);
};
xmlhttp.send();
));
The original GML
file is available at IOC stations GML. I made a copy of it locally to avoid CORS
.
Everything seems to be in place, but although that code loads the features, those features still need to have a geometry associated to them. This can be achieved by creating a ol.geom
, in this case a ol.geom.Point
.
Code:
var vector = new ol.layer.Vector({
source: new ol.source.Vector({
format: format
})
});
/** This is new **/
for (var i = 0; i < features.length; i++) {
var coordinates = [parseFloat(features[i].get('long')), parseFloat(features[i].get('lat'))];
// Create the new geometry object
var geom = new ol.geom.Point(ol.proj.transform(coordinates, 'EPSG:4326', 'EPSG:3857'));
features[i].setGeometry(geom);
}
/****/
vector.getSource().addFeatures(features);