Created
October 4, 2020 17:58
-
-
Save k-nut/b47b43817c3f18699b94c2d4c03532d3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// When a user views a map on a webiste, they probably want to see the map in relation to their current position. | |
// This snippets gets the user location and then tells the Leaflet map to fit the user location into the current view. | |
// This way, the developer of the website can create their map as always, setting a sensible default view. | |
// On page load, the user will be prompted for their location. If they give it, the map will zoom out so far | |
// that the user location as well as the original marker are visible. | |
// This way, if a user from another country views the map, they get a quick understanding for where this point | |
// is at all whereas a local can immediately see the precise position. | |
const myMap = L.map('mapid').setView([51.505, -0.09], 13); | |
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { | |
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' | |
}).addTo(myMap); | |
L.marker([51.5, 10.09]).addTo(myMap) | |
.bindPopup('A pretty CSS3 popup.<br> Easily customizable.') | |
.openPopup(); | |
function setInitialMapScaleBasedOnUserLocation(map) { | |
navigator.geolocation.getCurrentPosition((position) => { | |
const {latitude, longitude} = position.coords; | |
map.fitBounds([map.getBounds(), [latitude, longitude]]) | |
}); | |
} | |
setInitialMapScaleBasedOnUserLocation(myMap) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment