Maps and Routing
Leaflet
![]() |
image taken from http://leafletjs.com/ |
What is it?
As stated on the official website, „Leaflet is the leading open-source JavaScript library for mobile-friendly interactive maps. Weighing just about 38 KB of JS, it has all the mapping features most developers ever need.
Leaflet is designed with simplicity, performance and usability in mind. It works efficiently across all major desktop and mobile platforms, can be extended with lots of plugins, has a beautiful, easy to use and well-documented API and a simple, readable source code that is a joy to contribute to.“ (http://www.leafletjs.com)
In the library we can find tools to create things we already created with Google Maps, like markers and popups, and many more. Leaflet itself does not provide the map, you have to specify which map you want to use. I will go with OpenStreetMap, as I already mentioned in previous chapters, because I like its layout and it offers routing for many types of transport, and also for hiking or bicycles. Now lets go on and see some basics of how to use Leaflets. (You can find the whole documentation here).
How to use Leaflet
Although there is a pretty good tutorial that explains its use really well, lets see what we need to do before we start creating a map. First of all, we need to include the stylesheet and the script with the following HTML-code:
<link rel="stylesheet"
href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css"/>
and<script
src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"/>
Now, we have to create a div-tag with an id, in my case “mapid” (make sure the div-tag has a height!). Now we are ready to instantiate our map with javascript:
//This will create a map object and already set the
view point, but does not contain map layers!
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
//Now we have to add the so called tile layer to the map
//Be sure to add the attribution!
L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors',
maxZoom: 18,
}
).addTo(mymap);
In this case, I use the URL for OSM-tiles, if you want to use other maps, just search the right URL for it. Now we already have an OSM map on our website.
Add markers and other shapes
Adding markers is quite easy, you just need the coordinates:var marker = L.marker([51.5, -0.09]).addTo(mymap);
We can also add popups to markers, just write
marker.bindPopup("<b>Hello world!</b><br>I am a popup.");
As you can see, this is a really easy code that still gets us good results.
Here you can find the whole example.
No comments:
Post a Comment