OpenStreetMap & Leaflet.js – Free Map on Your Homepage, No Registration Needed

OpenStreetMap is a Free map of the world. You can even use it on your web pages without registering anywhere.
Leaflet.js is a JavaScript library that makes it easy to embed a map on a web page.
This article teaches you how to use Leaflet.js to show OpenStreetMap on your webpage.

You can simply download an example map-embedded-on-web-karvinen-2015.zip. Open index.html in a browser and you’ll see a map. It’s very simple, about 50 lines of JS+HTML.
It’s Free: My code is Free software under the BSD license, just like Leaflet.js. JQuery is Free software under the MIT license.
If you want to know how it works, read on. All this is already done in the zipped source.

HTML

The web page should have a div#map

<div id="map"></map>

You must add CSS to your page HEAD

<link rel="stylesheet" type="text/css" href="css/leaflet.css">

And JavaScript just before closing /BODY

<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/leaflet.js"></script>

Download Leaflet and jQuery

To use Leaflet.js and jQuery, you must download these javascript files.
leaflet-0.7.5.zip - Leaflet download page
jquery-2.1.4.min.js - JQuery download page

Write your Leaflet JavaScript

Div#map must have a height. You can set it in CSS or use jQuery to set it in JavaScript. If you leave the height at zero, you won’t see your map.

$("#map").css( {"height": "300px"});

Using Leaflet.js, the map initialization is just a couple of lines

 map = new L.Map('map');
 url = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
 opt = {}
 var layer = new L.TileLayer(url, opt);
 map.addLayer(layer);
 map.setView(new L.LatLng(60.1733244, 24.9410248), 9);

Enjoy Your Map

You should now have a map on your page. Well done!

Posted in Uncategorized | Tagged , , , , , , , | 1 Comment

One Response to OpenStreetMap & Leaflet.js – Free Map on Your Homepage, No Registration Needed

  1. James says:

    Thanks for the article!
    Cordova is great..
    I’ll definitely try this out
    Regards
    James
    Admin edit: removed extra link