Simple maps for your website based on Leaflet and OpenStreetMap

Simple maps for your website based on Leaflet and OpenStreetMap

This small tutorial will help you add simple maps based on open source data into your website. Map solution is based on Leaffet JS library and OpenStreetMap.org.

Definition of Leaflet from its official page:

Leaflet is a modern open-source JavaScript library for mobile-friendly interactive maps.

Definition of OpenStreetMap.org from their about:

OpenStreetMap is built by a community of mappers that contribute and maintain data about roads, trails, cafés, railway stations, and much more, all over the world. It's under open license.

I'm developing hosting website with map in a category. I was looking for a simple map solution with these features:

  • beautiful map layer
  • center map to particular country
  • ability to set zoom level
  • marker placed under capital city
  • custom icon marker

What you will need

Advertisement

<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>

Place this map code into your website

Special meta tag in <head> section:

 <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

and this code in <body> section:

<p id="map2" style="width: 300px; height: 250px"></p>
<script>
        var map = L.map('map2', {scrollWheelZoom: false, tap: false}).setView([51.165691,10.451526], 5);
        L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {
            maxZoom: 18,
            attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a>',
            id: 'examples.map-i86knfo3'
        }).addTo(map);
        L.marker([<?php print $fields[52.520007,13.404954]).addTo(map)
</script>

Short code explanation

  • FALSE value of scrollWheelZoom and tap disable map zooming by mouse scroll and simple tablet touch
  • 51.165691,10.451526 are coordinates of map center
  • 5 is zoom level
  • attribution sets credits for map data in right bottom map corner
  • 52.520007,13.404954 are coordinates of marker
  • you can use your own marker icon by placing this additional code into <body> JS

That's it. Fast and simple maps based on OpenStreetMap data. You can find demo here and life example here.

Advertisement

Post is listed in the Webdev category.