I have a simple map application written with Angular and Node.js There is search service that works fine and shows the results with geometry. After the search results I draw each result on map So far everything is fine. But after each result, I have to remove the old layers drawn on the map which I can not do it.

Here is my code:

onSearch(params: any) {
   if (params.target.value !== "") {
       this.httpClient.get('' + params.target.value).subscribe((response: any) => {
       this.searchResults = response
       this.mapService._map.removeLayer(this.vectorPolygon) // removing layers
       this.drawLocation(this.searchResults) // draw new ones
       return response
   } else {
       this.searchResults = []
drawLocation(results: any) {
results.map(res => {
  const format = new ol_format()
  const feature = format.readFeature(res._source.st_astext, {
    dataProjection: 'EPSG:4326',
    featureProjection: 'EPSG:3857'
  this.vectorSource = new ol_source_vector({
    features: [feature]
  this.vectorPolygon = new ol_layer_vector({
    source: this.vectorSource,
    displayInLayerSwitcher: false,
    style: this.styleMe(feature)
  • Define/create your vector layer and it's source outside drawLocation only once. Then before adding newly created feature to the vector source with .addFeature(feature) method, you can remove previous feature with the `.clear()' method. – TomazicM Apr 19 at 14:14
  • Thanks, should I use .addFeature(feature) because I didnt use it in my code. – myads mail Apr 21 at 6:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.