How to embed Open Street Map in a webpage (like Google Maps)

Narges Mirzaaghaei
3 min readJan 24, 2019

--

OpenStreetMap is a map of the world that is free to use and user-contributed. You can edit the map and like Wikipedia, if you do a good job it will stay otherwise someone will catch and roll it back.

You can use OSM, either as an iframe, or maybe you want to deploy your slippy map.

1- iframe

  • Search for a place you want
  • Right-click and click on “show address”
  • On the right side click on the share
  • Click on HTML and copy the iframe code and paste it into your HTML document

2. Deploy your map using Leaflet

You can embed OpenStreetMap into your website, just as you might with Google or Yahoo! maps. This can be done using Leaflet (leafletjs.com) which is a free open source JavaScript library with a light, easy-to-use API, with many plugins.

  • Include leaflet style to head of your HTML
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
  • Include leaflet javascript at the bottom of your body
<script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
  • Create a container for your map. You can use the <div> tag for this purpose and add dimension to it
<div id =”my-map” style = “width:800px; height:600px;”></div>
  • Add script for displaying a map. it should be added after leaflet.js
<script>
// Creating map options
var mapOptions = {
center: [17.385044, 78.486671],
zoom: 10
}

// Creating a map object
var map = new L.map(‘map’, mapOptions);

// Creating a Layer object
var layer = new L.TileLayer(‘http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png’);

// Adding layer to the map
map.addLayer(layer);
</script>
  • Complete markup
<!DOCTYPE html>
<html>
<head>
<title>OSM and Leaflet</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
</head>
<body>
<div id = "map" style = "width: 900px; height: 580px"></div>
<script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<script>
// Creating map options
var mapOptions = {
center: [17.385044, 78.486671],
zoom: 10
}

// Creating a map object
var map = new L.map('map', mapOptions);

// Creating a Layer object
var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');

// Adding layer to the map
map.addLayer(layer);
</script>
</body>

</html>

we are done!

If you are interested in more detailed information I recommend you view a great tutorial on the Tutorialspoint website

You may also like to read:

How to find an address or place in OpenStreetMap

How to get latitude and longitude from a click event on Open Street Map

How to customize the OpenStreetMap marker icon and binding popup

How to display multiple locations on the map and show related information on user hover(like booking.com)

--

--