Is there any way to add a kml vector in openlayer 3 like this but the kml is from a string variable?
var vector = new ol.layer.Vector({
source: new ol.source.Vector({
url: 'https://openlayers.org/en/v4.2.0/examples/data/kml/2012-02-10.kml',
format: new ol.format.KML()
})
});
I tried this code but it doesn't work.
var kmlString = result;
var features = new ol.format.KML().readFeatures(kmlString);
var KMLvectorSource = new ol.source.Vector({
features: features
});
var KMLvector = new ol.layer.Vector({ source: KMLvectorSource });
//KMLvector.addFeatures(features);
map.addLayer(KMLvector);
Thanks in advance.
You are missing the projection definition and transformation for your kml features.
The kml features exist in https://openlayers.org/en/v4.2.0/examples/data/kml/2012-02-10.kml
are projected in EPSG:4326
while your map is projected in EPSG:3857
. For kml is common to be projected in 4326
so in most cases the EPSG code for kml should be 4326.
Now back to your problem. Change this line:
var features = new ol.format.KML().readFeatures(kmlString);
To this:
var features = new ol.format.KML().readFeatures(kmlString,{
dataProjection:'EPSG:4326',
featureProjection:'EPSG:3857'
});