6 :: Mapbox and Geolocation

Shortly after doing some reading about Mapbox I promptly made a new category for posts dedicated to it.  They do beautiful work. The improvements they’ve made to the in-browser editor of OpenStreetMap are immediately apparent.

I will be getting into editing OpenStreetMap sometime shortly, I suspect, but for today’s challenge, I’m going to simply use Mapbox.js to create a map with geolocation on it. But with Mapbox’s straightforward examples that they kindly provide, this is hardly a challenge at all. Just a simple copy, save, and upload:

<!DOCTYPE html>
<script src='http://api.tiles.mapbox.com/mapbox.js/v1.0.2/mapbox.js'></script>
<link href='http://api.tiles.mapbox.com/mapbox.js/v1.0.2/mapbox.css' rel='stylesheet' />
<!--[if lte IE 8]>
<link href='http://api.tiles.mapbox.com/mapbox.js/v1.0.2/mapbox.ie.css' rel='stylesheet' >
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }

#geolocate {
background: #fff;
position: absolute;
top: 50%;
left: 50%;
width: 158px;
margin-left: -80px;
z-index: 1000;
font: 13px/18px;
text-align: center;
padding: 10px 0;
color: #3C4E5A;
display: block;
border: 1px solid #BBB;
-webkit-border-radius: 3px;
border-radius: 3px;

#geolocate:hover {
background: #ECF5FA;
<div id='map'></div>
<a href='#' id='geolocate'>Find me</a>
<script type='text/javascript'>
var map = L.mapbox.map('map', 'examples.map-4l7djmvo');
var geolocate = document.getElementById('geolocate');

// This uses the HTML5 geolocation API, which is available on
// most mobile browsers and modern browsers, but not in Internet Explorer
// See this chart of compatibility for details:
// http://caniuse.com/#feat=geolocation
if (!navigator.geolocation) {
geolocate.innerHTML = 'geolocation is not available';
} else {
geolocate.onclick = function (e) {

// Once we've got a position, zoom and center the map
// on it, and add a single marker.
map.on('locationfound', function(e) {

type: "Feature",
geometry: {
type: "Point",
coordinates: [e.latlng.lng, e.latlng.lat]
properties: {
'marker-color': '#000',
'marker-symbol': 'star-stroked'

// And hide the geolocation button

// If the user chooses not to allow their location
// to be shared, display an error message.
map.on('locationerror', function() {
geolocate.innerHTML = 'position could not be found';


And here’s my live-demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *