Radex
Radex

Reputation: 8577

How to add a marker on a map on openlayer?

I am using openlayer, but I am not able to add a marker with lat/long on the map. Could you please point me out in a right direction, below a sample of my code:

let map = new ol.Map({
  target: 'map',
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    })
  ],
  view: new ol.View({
    center: ol.proj.transform([37.41, 8.82], 'EPSG:4326', 'EPSG:3857'),
    zoom: 4
  })
})
let layerCloud = new ol.layer.Tile({
  source: new ol.source.XYZ({
    url: api.mapTemperature()
  })
})
map.addLayer(layerCloud)

Upvotes: 1

Views: 3217

Answers (1)

sudhir shakya
sudhir shakya

Reputation: 897

You can add a marker by adding a new Vector layer with the style set to display an image of a pin. The code below will add a pin to the center of the map.

const center = map.getView().getCenter();
const pinnedLocation = ol.proj.transform(center, 'EPSG:3857', 'EPSG:4326');
const feature = new ol.Feature(new ol.geom.Point(center));
const pinLayer = new ol.layer.Vector ({
  source: new ol.source.Vector ({
    features: [feature]
  }),
  style: new ol.style.Style ({
    image: new ol.style.Icon({
      src: 'http://openlayers.org/en/v3.8.2/examples/data/icon.png'
    })
  })
});
map.addLayer (pinLayer);

Upvotes: 3

Related Questions