Geolocation

Finding the user's position
Find me
Select all
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Geolocation</title>
  
  <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' />
  <script src='//api.tiles.mapbox.com/mapbox.js/v1.5.0/mapbox.js'></script>
  <link href='//api.tiles.mapbox.com/mapbox.js/v1.5.0/mapbox.css' rel='stylesheet' />
  
  <style>
    body { margin:0; padding:0; }
    #map { position:absolute; top:0; bottom:0; width:100%; }
  </style>
</head>
<body>
<style>
#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;
}
</style>
<div id='map'></div>
<a href='#' id='geolocate'>Find me</a>
<script>
var map = L.mapbox.map('map', 'examples.map-9ijuk24y');
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) {
        e.preventDefault();
        e.stopPropagation();
        map.locate();
    };
}

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

    map.markerLayer.setGeoJSON({
        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
    geolocate.parentNode.removeChild(geolocate);
});

// 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';
});
</script>
The code and documentation to mapbox.js is hosted on GitHub where you can contribute changes and improvements.