Reputation: 190
I wonder if someone can point me in the right direction. I'm trying to add multiple markers/icons to an OSM map using OpenLayers 4.6.4.
The following code renders the map without any problem:
<script src="https://openlayers.org/en/v4.6.4/build/ol.js"></script>
<script type='text/javascript'>
var map = new ol.Map({
target: 'mapdiv',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: ol.proj.fromLonLat([-0.1526069, 51.4790309]),
zoom: 14
})
});
</script>
I've tried searching on the OpenLayers website for information how to add a marker but it states markers are deprecated! All I want to do is add some pins/markers to the map to display site locations.
I've also tried other versions of OpenLayers 2.13.1, 2.14 and 3.0 without any success.
Any assistance would be greatly appreciated.
Upvotes: 3
Views: 12184
Reputation: 5019
The old markers are deprecated. You should use geometry Points with Icon style. Icon Symbolizer Example is the one you are looking for:
document.addEventListener("DOMContentLoaded", function() {
var iconFeature1 = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([-0.1526069, 51.4790309]), ),
name: 'Somewhere',
});
var iconFeature2 = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([-0.1426069, 51.4840309])),
name: 'Somewhere else'
});
// specific style for that one point
iconFeature2.setStyle(new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: 'https://upload.wikimedia.org/wikipedia/commons/thumb/9/93/Map_marker_font_awesome.svg/200px-Map_marker_font_awesome.svg.png',
})
}));
const iconLayerSource = new ol.source.Vector({
features: [iconFeature1, iconFeature2]
});
const iconLayer = new ol.layer.Vector({
source: iconLayerSource,
// style for all elements on a layer
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: 'https://openlayers.org/en/v4.6.4/examples/data/icon.png'
})
})
});
const map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
}),
iconLayer
],
view: new ol.View({
center: ol.proj.fromLonLat([-0.1526069, 51.4790309]),
zoom: 14
})
});
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.5/ol.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.5/ol-debug.js"></script>
<div id="map" class="map"></div>
Upvotes: 8