Leaflet.js - Current Location

Show your current location in Leaflet.js/OpenStreetMap. Utilizes geoplugin.net & the browser's built in geolocation.

HTML

<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.4/leaflet.css">
<script src="http://cdn.leafletjs.com/leaflet-0.4/leaflet.js"></script>
<script src="http://maps.stamen.com/js/tile.stamen.js"></script>
<div id="map"></div>

CSS

#map { height: 400px; }

JavaScript

var map = L.map('map').setView([51.505, -0.09], 13);

var layer = new L.StamenTileLayer('watercolor');
map.addLayer(layer);

var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
    var mapTiles = new L.TileLayer(osmUrl, {
    attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
    maxZoom: 18
});

// add the CloudMade layer to the map set the view to a given center and zoom
map.addLayer(mapTiles);

// add location via browser geolocation
function displayLocation(position) {
    console.log('position', position);
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    L.marker([lat, lng]).addTo(map);
    console.log('{longitude:' + lng + ', latitude:' + lat + '}'); 
    map.setView([lat, lng], 16);
}
            
navigator.geolocation.getCurrentPosition(displayLocation);
            
// get location via geoplugin.net
jQuery(document).ready(function($) {
    jQuery.getScript('http://www.geoplugin.net/javascript.gp', function() {
    var country = geoplugin_countryName();
    var zone = geoplugin_region();
    var district = geoplugin_city();
    console.log("Your location is: " + country + ", " + zone + ", " + district);
    var lat = geoplugin_latitude();
    var lng = geoplugin_longitude();
    L.marker([lat, lng]).addTo(map);
    console.log('{longitude:' + lng + ', latitude:' + lat + '}');
        
        map.setView([lat, lng], 13);
    });
});