← Back to the list of examples
In this example, you'll learn how to create a fullscreen map tuned for mobile devices like iPhone, iPad or Android phones, and how to easily detect and use the current user location.
First we'll take a look at the HTML & CSS code of the page. To make our map div
element stretch to all available space (fullscreen), we can use the following CSS code:
body {
padding: 0;
margin: 0;
}
html, body, #map {
height: 100%;
}
Also, we need to tell the mobile browser to disable scaling of the page and set it to its actual size by placing the following line in the head
section:
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
We'll now initialize the map in the JavaScript code exactly like we did in the quick start guide, but won't set the map view yet:
var map = new L.Map('map');
var cloudmadeUrl = 'http://{s}.tile.cloudmade.com/YOUR-API-KEY/997/256/{z}/{x}/{y}.png',
cloudmadeAttribution = 'Map data © 2011 OpenStreetMap contributors, Imagery © 2011 CloudMade',
cloudmade = new L.TileLayer(cloudmadeUrl, {maxZoom: 18, attribution: cloudmadeAttribution});
map.addLayer(cloudmade);
Leaflet has a very handy shortcut for zooming the map view to the detected location — locateAndSetView method, replacing the usual setView
method in the code:
map.locateAndSetView(16);
Here we specify 16 as the maximum zoom when setting the map view automatically. Now we have a working fullscreen mobile map! But what if we need to do something after the geolocation completed? Here's what the locationfound
and locationerror
events are for. Let's for example add a marker in the detected location, showing accuracy in a popup, by adding an event listener to locationfound
event before the locateAndSetView
call:
map.on('locationfound', onLocationFound);
function onLocationFound(e) {
var radius = e.accuracy / 2;
var marker = new L.Marker(e.latlng);
map.addLayer(marker);
marker.bindPopup("You are within " + radius + " meters from this point").openPopup();
var circle = new L.Circle(e.latlng, radius);
map.addLayer(circle);
}
Excellent! But it would also be nice to show an error message if the geolocation failed:
map.on('locationerror', onLocationError);
function onLocationError(e) {
alert(e.message);
}
Now the example is complete — try it on your mobile phone: View the full example →
Next steps would be to take a look at the detailed documentation and browse other examples.
© 2011 CloudMade. Map data © 2011 OpenStreetMap contributors, CC-BY-SA.