Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I add a marker to Open Layers map?

Currently building a map app. Trying all the methods I find in the internet to add a marker, still doesn’t work. Am I doing it wrong?

Here’s my Angular code:

Somehow, it’s much easier with Leaflet, but I don’t want to abandon Open Layers that early.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export class MapComponent implements OnInit{
  
  map! : Map;
  marker! :any;
  center = fromLonLat([5.5697, 50.6330]);
  iconFeature = new Feature({
    geometry : new Point(fromLonLat([5.5697, 50.6330]))
  })
  
  ngOnInit(): void {

    this.map = new Map({
      view : new View({
        center : this.center,
        zoom : 0
      }),
      layers : [

         new LayerVector({
          source : new SourceVector({
            features : [this.iconFeature]
          }),
          style : new Style({
            image : new Icon({
              anchor : [0.5, 46],
              src : '../assets/istockphoto-1153114937-2048x2048-removebg-preview.png'
            })
          })
         })
         new TileLayer({
       source : new OSM()
         })
      ],
      target :  "map"
    })   
  }

}

>Solution :

can u try this example of code

import { Map, View } from 'ol';
import { Tile as TileLayer, Vector as LayerVector } from 'ol/layer';
import { OSM, Vector as SourceVector } from 'ol/source';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import { fromLonLat } from 'ol/proj';
import { Icon, Style } from 'ol/style';

export class MapComponent implements OnInit{
  
  map!: Map;
  center = fromLonLat([5.5697, 50.6330]);

  ngOnInit(): void {

    const marker = new Feature({
      geometry: new Point(fromLonLat([5.5697, 50.6330]))
    });

    const markerLayer = new LayerVector({
      source: new SourceVector({
        features: [marker]
      }),
      style: new Style({
        image: new Icon({
          anchor: [0.5, 1],
          src: '../assets/istockphoto-1153114937-2048x2048-removebg-preview.png'
        })
      })
    });

    this.map = new Map({
      view: new View({
        center: this.center,
        zoom: 0
      }),
      layers: [
        new TileLayer({
          source: new OSM()
        }),
        markerLayer
      ],
      target: 'map'
    });
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading