Monday, 15 January 2018

carto - Does Cartodb have a function to change center location based on user location?


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

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...