Using LeafletJS for showing maps on a web page

Your first reaction might be: “Hey, dum-dum, why don’t you just use Google Maps or Bing Maps? They’ve been around forever!”

True, and the reason I ended up not using them… is because they’ve been around forever. They are very involved, very heavy API’s.

In present-day, in our fast-paced development world, we now know what JavaScript libraries should look like – and neither Bing nor Google are it. They are way, way, way too complicated and require way too much overhead to even get started.

So, I did some market research and found many people raving about:

http://www.leafletjs.com

Once I looked into it, I was quite impressed. In fact, I was impressed for several reasons:

  • The maps are very nice – much “richer” than Bing or Google (but that’s subjective).
  • The maps look and act equally well in a desktop browser and on a mobile/tablet browser – this include mouse-wheel zooming, or pinch/push zooming.
  • There are no practical limits of use on the maps, you don’t need to register your app or pay for the service. Just be respectful and responsible with your usage – and include their credit/attribution on the map.
  • The API is stupid-simple to implement (see below).

Here is an example of how the street maps look:

image

the underlying provider of the map data is: www.openstreetmap.org and MapQuest by the way.

How to show a map:
If you are using Visual Studio, add a NuGet package called “JavaScript library for interactive maps.” – or you can just search for “leaflet”:

image

Now, on the page where you want the map, add the appropriate javascript and css to the <head> of the HTML document:

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

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Then, add a <div> where you want the map to be (make sure to set the height):

<div id="map" style="height: 400px"></div>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

and then finally, some JavaScript to load the map and set some defaults:

var map;
var ajaxRequest;
var plotlist;
var plotlayers = [];

function initializeMap() {
    map = new L.Map('map');

    // REQUIRED: create the tile layer with correct attribution
    var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
    var osmAttrib = 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors';
    var osm = new L.TileLayer(osmUrl, { minZoom: 8, maxZoom: 20, attribution: osmAttrib });

    // Set default center (Hartford, CT in this case - with a zoom level of 17)
    map.setView(new L.LatLng(41.7656874, -72.680087), 17);
    map.addLayer(osm);
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Now, you might think: “Can’t I get the users current position?” Well, you can ask for it. You can take advantage of that browser feature. This works in desktop browsers as well as mobile:

function onGetCurrentPosition(location) {
    var latitude = location.coords.latitude;
    var longitude = location.coords.longitude;
    var zoomLevel = 17;

    map.setView(new L.LatLng(latitude, longitude), zoomLevel);
}
function onError() {
    // Do nothing
}

$().ready(function () {

    initializeMap();

    // Attempt to get the users current location.
    if (navigator.geolocation)
        navigator.geolocation.getCurrentPosition(onGetCurrentPosition, onError);
});

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

This starts in the $().ready (which is when the DOM has been fully-loaded). We ask the user if we can get their location (with .getCurrentPosition(..)). If they agree, then the onGetCurrentPosition(..) event handler gets called, re-centers the map on the current location and sets the zoom level to 17 – which is a good street-level. Easy-peasy, right?!

Next Steps:
The API documentation on the leaflet site is excellent. So, if you want to add pushpins, labels, etc – they have excellent canonical examples there.

This service is really great for showing interactive maps on a webpage, but that’s pretty much where it stops. If you need other geolocation services – like looking up coordinates, getting directions, or verifying an address – you still will need one of the heavier API’s like Google, Bing, or MapQuest. Since Leaflet partners with MapQuest, and since MapQuest has open (and free) API’s, I might prefer them slightly, but we’ll see.

Bottom line for me, leafletjs is a slam-dunk for showing a map on a web page!

Posted in ASP.NET, ASP.NET MVC, Cloud Computing, Computers and Internet, Development Tools, General, JQuery, Mobile, New Technology, Uncategorized, WindowsPhone

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Archives
Categories

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 5 other followers

%d bloggers like this: