Working with OpenLayers 4 | Part 2 — Using markers or points on the map

Mohit Gupta
Attentive AI Tech Blog
2 min readMay 10, 2018
Working with OpenLayers 4 | Part 2 — Using markers or points on the map

In the Previous Part Working with OpenLayers 4 | Part 1 — Creating the first application, we made a basic openlayer map page and initiated the map at the desired location and desired zoom level.

We will start with the previous codes and make a marker on New York’s town hall.

In openlayers, actually there is no such thing like marker, it has only layers and features like point, line, and polygon. So, to make the marker we will make a feature object, will make source object for this feature, will add this object to a new layer and add this new layer over the map so that we can see the marker.

Making a new feature marker:

var marker = new ol.Feature({
geometry: new ol.geom.Point(
ol.proj.fromLonLat([-74.006,40.7127])
), // Cordinates of New York's Town Hall
});

Now let’s make a source for this feature :

var vectorSource = new ol.source.Vector({
features: [marker]
});

If you want to add multiple markers, you can add multiple feature objects array to the feature key of the source object, this way you can show more than one marker on the map.

Now make a new layer and add it to the map:

var markerVectorLayer = new ol.layer.Vector({
source: vectorSource,
});
map.addLayer(markerVectorLayer);

Now the whole map.js file will look like this:

var baseMapLayer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
target: 'map',
layers: [ baseMapLayer],
view: new ol.View({
center: ol.proj.fromLonLat([-74.0061,40.712]),
zoom: 7 //Initial Zoom Level
})
});
//Adding a marker on the mapvar marker = new ol.Feature({
geometry: new ol.geom.Point(
ol.proj.fromLonLat([-74.006,40.7127])
), // Cordinates of New York's Town Hall
});
var vectorSource = new ol.source.Vector({
features: [marker]
});
var markerVectorLayer = new ol.layer.Vector({
source: vectorSource,
});
map.addLayer(markerVectorLayer);

I have also separated the base layer into an object with the variable named baseMapLayer for a better understanding of the codes.

Now if you run the code and see the results, you will see a marker on the map.

Blue marker on the city town hall

You can download the full code from this jsfiddle or Github repo.

And if you enjoyed this post, share it on Facebook and Twitter. I Love Sharing.
You can also follow me on twitter: here

--

--