what add marker to map openlayer 5 with angular 6

3.4k views Asked by At

I'm using the OpenLayers 5 for my project in angular 6. I implemented it to show a map and it is working :-). But I can't make it show any markers, please help me!!! Show examples with this version OpenLayers...

import OlMap from 'ol/Map';
import OlXYZ from 'ol/source/XYZ';
import OlTileLayer from 'ol/layer/Tile';
import OlView from 'ol/View';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';

import {fromLonLat} from 'ol/proj';

export class MyComponent implements OnInit {
    map: OlMap;
    source: OlXYZ;
    layer: OlTileLayer;
    view: OlView;
    marker: Feature;


ngOnInit() {
    this.marker = new Feature({
        geometry: new Point([27.46164, 53.902257])
    });

    this.source = new OlXYZ({
        url: 'http://tile.osm.org/{z}/{x}/{y}.png',
        features: [this.marker]
    });

    this.layer = new OlTileLayer({
        source: this.source
    });

    this.view = new OlView({
        center: fromLonLat([27.56164, 53.902257]),
        zoom: 14
    });

    this.map = new OlMap({
        target: 'map',
        layers: [this.layer],
        view: this.view
    });
}

}

1

There are 1 answers

3
pzaenger On BEST ANSWER

You need a vector layer and a vector source to add features. Something like the following:

import Map from 'ol/Map';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import View from 'ol/View';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import XyzSource from 'ol/source/XYZ';
import TileLayer from 'ol/layer/Tile';
    
import { fromLonLat } from 'ol/proj';
    
export class MyComponent implements OnInit {

  map: Map;
  vectorSource: VectorSource;
  vectorLayer: VectorLayer;
  xyzSource: XyzSource;
  tileLayer: TileLayer;
  view: View;
  marker: Feature;
    
  ngOnInit() {

    // Feature and vector
    this.marker = new Feature({
      geometry: new Point(fromLonLat([27.46164, 53.902257]))
    });
    
    this.vectorSource = new VectorSource({
      features: [this.marker]
    });
    
    this.vectorLayer = new VectorLayer({
      source: this.vectorSource
    });

    // XYZ
    this.xyzSource = new XyzSource({
      url: 'http://tile.osm.org/{z}/{x}/{y}.png'
    });
    
    this.tileLayer = new TileLayer({
      source: this.xyzSource
    });

    // View and map
    this.view = new View({
      center: fromLonLat([27.56164, 53.902257]),
      zoom: 14
    });
    
    this.map = new Map({
      target: 'map',
      layers: [this.tileLayer, this.vectorLayer],
      view: this.view
    });
  }
}