[GIS] Changing vector layer dynamically using OpenLayers 4

geojsonopenlayersvector

I need dynamically change vector layer on map, which is represented by some route in geojson. This new geojson I get from my service, so I have function changeRoute, which I will call in ajax on success :

function changeRoute(newRouteInGeoJSON) {
    // change vector layer here and redraw it by new Geojson...
}

And here is my actual code :

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

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

var markersCooord = getMarkersCoordinates();


var sourceFeature = new ol.Feature({
  geometry: new ol.geom.Point(ol.proj.transform(markersCooord[0], 'EPSG:4326',
  'EPSG:3857'))
});

var targetFeature = new ol.Feature({
  geometry: new ol.geom.Point(ol.proj.transform(markersCooord[1], 'EPSG:4326',
  'EPSG:3857'))
});

var sourceSource = new ol.source.Vector({
  features: [sourceFeature] //add an array of features
});
var targetSource = new ol.source.Vector({
  features: [targetFeature] //add an array of features
});

var sourceStyle = new ol.style.Style({
  image: new ol.style.Icon(({
    anchor: [0.5, 1],
    src: 'data/source.png'
  }))
});
var targetStyle = new ol.style.Style({
  image: new ol.style.Icon(({
    anchor: [0.5, 1],
    src: 'data/target.png'
  }))
});

var sourceLayer = new ol.layer.Vector({
  source: sourceSource,
  style: sourceStyle
});
var targetLayer = new ol.layer.Vector({
  source: targetSource,
  style: targetStyle
});

var map = new ol.Map({
    target: 'map',
    layers: [
        new ol.layer.Tile({
            source: new ol.source.XYZ({
                url: 'http://10.0.2.2:8080/geoserver/gwc/service/tms/1.0.0/Bachelor%3Av_slovensko_group@EPSG%3A3857@png/{z}/{x}/{-y}.png'
            })
        }),
        vectorLayer,
        sourceLayer,
        targetLayer
    ],
    view: new ol.View({
        center: ol.proj.fromLonLat([22.00, 48.82]),
        minZoom: 10,
        maxZoom: 18,
        zoom: 10,
    }),
    controls: []
});
//var extent = source.getExtent();
//map.getView().fit(extent, map.getSize());

function getMarkersCoordinates() {
    var start, end;
    var isFirst = true;

    for (var i = 0; i < routeJSON.features.length; i++) {
        if (isFirst) {
            if (routeJSON.features[i].geometry != null) {
            start = routeJSON.features[i].geometry.coordinates[0];
            isFirst = false;
        }
        } else {
            if (routeJSON.features[i].geometry != null) {
                for (var j = 0; j < routeJSON.features[i].geometry.coordinates.length; j++)
                    end = routeJSON.features[i].geometry.coordinates[j];
                }
            }
        }
        return [start, end];
}

My current scripts using geojson to draw route, and calculate first and last coordinates to create geopoints for pins.

How do I use the function changeRoute to change my vector layer to new geojson?

Best Answer

just hold the vector layer you first added to the map and do the following

  1. clear any existing features

    vectorLayer.getSource().clear();

  2. Declare a new geojson format to parse the supplied route

    var format = new ol.format.GeoJSON({ featureProjection:"EPSG:3857" });

  3. Use the format to parse your new geojson and add the features to the source

    vectorLayer.getSource().addFeatures(format.readFeatures(routeJSON))

so propably your function should be something like:

function changeRoute(newRouteInGeoJSON) {
vectorLayer.getSource().clear();
var format = new ol.format.GeoJSON({
    featureProjection:"EPSG:3857"
    });
vectorLayer.getSource().addFeatures(format.readFeatures(newRouteInGeoJSON));
}
Related Question