I would like to have the map open up a the users current location. I only see documentation for setting the center on init, I would like it to be dynamic..
Answer
this example shows how it can be done
add the following function to detect user location
// credit: http://html5doctor.com/finding-your-position-with-geolocation/
function detectUserLocation(){
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.watchPosition(
mapToPosition,
alertError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
alert("Geolocation is not supported by this browser");
}
function alertError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
}
if the user allows it, the above function calls mapToPosition
to update the map to that location
function mapToPosition(position) {
lon = position.coords.longitude;
lat = position.coords.latitude;
map.setView(new L.LatLng(lat,lon), 7);
new L.CircleMarker([lat,lon],{radius: 4}).addTo(map);
}
If you want it to be dynamic, you could trigger detectUserLocation()
from a button
$('#button').on('click', detectUserLocation);
No comments:
Post a Comment