An Ultimate Guide to Openlayers: Free Maps for Web

This article is dedicated to OpenLayers, a free maps service for the web. Openlayers is a decent alternative for the Google Maps. In this tutorial I will tell you how to use the basic features in Openlayers.

Openlayer Maps

Starting with OpenLayers

Here is how to create a basic map with OpenLayers. The only thing you need to do is to add the Openlayers JS file in your web page.

<script src="http://openlayers.org/dev/OpenLayers.js"></script>
//Html
<div id="map"></div>

//JavaScript
var map = new OpenLayers.Map('map');
var osm_layer = new OpenLayers.Layer.OSM();
map.addLayers([osm_layer]);
See the Pen OpenLayers Basic Map by Arvind Bhardwaj (@arvind) on CodePen.

Adding Zoom Level and Center Location

//Convert the coordinates into GPS format
var cent_lonlat = new OpenLayers.LonLat(77.2300, 28.6100)
.transform(new OpenLayers.Projection('EPSG:4326'), new OpenLayers.Projection('EPSG:3857'));

//The layers
var osm_layer = new OpenLayers.Layer.OSM();

var map = new OpenLayers.Map({
div: "map",
displayProjection: new OpenLayers.Projection("EPSG:4326", "EPSG:3857"),
center: cent_lonlat,
zoom: 5,
layers: [osm_layer]
});

Add Google Maps Layer to OpenLayers

OpenLayers are flexible enough to support a number of layers like Google Maps. Here is how to add Google Map layers to OpenLayers:

See the Pen Add Google Layers to Openlayers Map by Arvind Bhardwaj (@arvind) on CodePen.

Add Zoom Scale to OpenLayers

By default Openlayers provide two buttons for “Zoomin” and “Zoomout”. If you want complete scale for zoom, just add the following line:

map.addControl(new OpenLayers.Control.PanZoomBar());
See the Pen Add Zoom Scale to Openlayers by Arvind Bhardwaj (@arvind) on CodePen.

Add Markers & Popups to Openlayers

For adding markers to our Openlayer maps, first of all we need to add a new “Vector Layer” to the map. Then a “Select” control is added to this vector layer. This select control will allow us to click on the layer so that we can add markers on the clicked location.

See the Pen Add Marker and Popup to Openlayers Map by Arvind Bhardwaj (@arvind) on CodePen.

Draw Polygon on the Openlayers Map

Openlayers support drawing shapes on the maps. Here is an example of how to do that:

See the Pen Add Polygon and Drawing to Openlayer Maps by Arvind Bhardwaj (@arvind) on CodePen.

Edit the Polygon on Openlayer Map

See the Pen Edit Polygons on Openlayers Map by Arvind Bhardwaj (@arvind) on CodePen.

Written by Arvind Bhardwaj

Arvind is a Magento and WordPress expert with more than 6 years of industry wide experience.

Website: http://www.webspeaks.in/