Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Leaflet.js Essentials

You're reading from   Leaflet.js Essentials Create interactive, mobile-friendly mapping applications using the incredibly light yet powerful Leaflet.js platform.

Arrow left icon
Product type Paperback
Published in Aug 2014
Publisher
ISBN-13 9781783554812
Length 180 pages
Edition 1st Edition
Languages
Arrow right icon
Toc

Mobile mapping

The maps you have made so far have been tested on the desktop. One of the benefits of mapping in JavaScript is that mobile devices can run the code in a standard web browser without any external applications or plugins. Leaflet runs on mobile devices, such as iPhone, iPad, and Android devices. Any web page with a Leaflet map will work on a mobile device without any changes; however, you probably want to customize the map for mobile devices so that it works and looks like it was built specifically for mobile.

Lastly, the L.map() class has a locate() method, which uses the W3C Geolocation API. The Geolocation API allows you to find and track a user's location using the IP address, the wireless network information, or the GPS on a device. You do not need to know how to use the API; Leaflet handles all of this when you call locate().

HTML and CSS

The first step in converting your Leaflet map to a mobile version is to have it display properly on mobile devices. You can always tell when you open a website on your phone whether the developer took the time to make it mobile-accessible. How many times have you been on a website where the page loads and all you can see is the top-left corner, and you have to zoom around to read the page. It is not a good user experience. In LeafletEssentials.html in the <head> tag after the <link> tag for the CSS file, add the following code:

<style>

body{
padding: 0;
margin: 0;
    }
html, body, #map {
height: 100%;
        }
</style>

In the preceding CSS code, you set the padding and margin values to 0. Think of a web page as a box model, where each element exists in its own box. Each box has a margin, which is the space between it and other boxes, and also padding, which is the space between the content inside the box and the box border (even if a border is not physically drawn). Setting the padding and margin values to 0 makes the <body> content fit to the size of the page. Lastly, you set the height value of the <html>, <body>, and <div id = 'map'> elements to 100%.

Note

In CSS, # is the ID selector. In the code, #map is telling us to select the element with the id = 'map' line. In this case, it is our <div> element that holds the map.

The following diagram shows an overview of the settings for the web page:

HTML and CSS

The last step is to add the following code in the <head> section and after the </title> element:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

The preceding code modifies the viewport that the site is seen through. This code sets the viewport to the width of the device and renders it by a ratio of 1:1. Lastly, it disables the ability to resize the web page. This, however, does not affect your ability to zoom on the map.

Creating a mobile map with JavaScript

Now that you have configured the web page to render properly on mobile devices, it is time to add the JavaScript code that will grab the user's current location. For this, perform the following steps:

  1. Create the map instance, but do not use setView:
    var map = L.map('map');
  2. Add a tile layer:
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(map);
  3. Define a function to successfully find the location:
    Function foundLocation(e){}
  4. Define a function to unsuccessfully find the location:
    functionnotFoundLocation(e){}
    
  5. Add an event listener for foundLocation() and notFoundLocation():
    map.on('locationfound', foundLocation);
    map.on('locationerror', notFoundLocation);
  6. Use locate() to set the map view:
    map.locate({setView: true, maxZoom:10});

The code creates the map and adds a tile layer. It then skips over the functions and event listeners and tries to locate the user. If it is able to locate the user, it runs the code in foundLocation() and sets the view to the latitude and longitude of the user. If it does not locate the user, it executes the code in notFoundLocation() and displays a zoomed-out world map.

To make this example more usable, add the following code to notFoundLocation():

function notFoundLocation(e){
alert("Unable to find your location. You may need to enable Geolocation.");}

The alert() function creates a pop up in the browser with the message passed as a parameter. Anytime that the browser is unable to locate the user, they will see the following message. While some devices do not have location capabilities, at times, they need to be allowed in their security settings:

Creating a mobile map with JavaScript

Now, add the following code to foundLocation():

function foundLocation(e){
varmydate = new Date(e.timestamp);
L.marker(e.latlng).addTo(map).bindPopup(mydate.toString());
     }

The preceding code will run when the user's location is found. The e in foundLocation(e) is an event object. It is sent when an event is triggered to the function that is responsible for handling that specific event type. It contains information about the event that you will want to know. In the preceding code, the first event object we grab is the timestamp object. If you were to display the timestamp in a pop up, you would get a bunch of numbers: 1400094289048. The timestamp is the number of milliseconds that have passed since January 1, 1970 00:00:00 UTC. If you create an instance of the date class and pass it to the timestamp object, you receive a human-readable date. Next, the code creates a marker. The latitude and longitude are stored in e.latlng. You then add the marker to the map and bind a pop up. The pop up needs a string as a parameter, so you can use the toString() method of the date class or use String(mydate) to convert it. The following screenshot shows the pop up with the date and time when the user clicked on it:

Creating a mobile map with JavaScript
You have been reading a chapter from
Leaflet.js Essentials
Published in: Aug 2014
Publisher:
ISBN-13: 9781783554812
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image