I watch the visitors position and stores the current coordinates in two variables, latitude and longitude. When the visitor clicks on the map, the new marker's coordinates will be stored in another two variables, click_latitude and click_longitude.
When this is done, I want to show the marker's coordinates in the span .test as text. The problem is that coordinates_click (which contains click_latitude and click_longitude) are always empty! The coordinates for the marker are only stored in the variables within map.on('click', function(e1) { ... } and can not be accessed outside the function.
Why and how can I fix this?
if(navigator.geolocation) {
// VARIABLES
var gps_timeout = 10 * 1000 * 1000;
// MAP
map = L.map('map', {
maxZoom: 17,
minZoom: 7
}).setView([59.380767, 13.503022], 13);
// MAP (copyright)
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data © OpenStreetMap contributors'
}).addTo(map);
// GPS
navigator.geolocation.watchPosition(success, error, {
enableHighAccuracy: true,
timeout: gps_timeout,
maximumAge: 0
});
// ADD MARKER
map.on('click', function(e1) {
// IF
if(typeof(marker) === 'undefined') {
marker = new L.marker(e1.latlng).addTo(map);
var position = marker.getLatLng();
var click_latitude = position.lat.toFixed(6);
var click_longitude = position.lng.toFixed(6);
map.panTo(new L.LatLng(click_latitude, click_longitude));
// IF
} else {
marker.setLatLng(e1.latlng);
var position = marker.getLatLng();
var click_latitude = position.lat.toFixed(6);
var click_longitude = position.lng.toFixed(6);
map.panTo(new L.LatLng(click_latitude, click_longitude));
}
});
// IF
} else {
// error handler
}
function success(position) {
// VARIABLES
latitude = position.coords.latitude.toFixed(6);
longitude = position.coords.longitude.toFixed(6);
coordinates_current = latitude + ',' + longitude;
coordinates_click = window.click_latitude + ',' + window.click_longitude;
// IF
if(coordinates_click !== '') {
$('.test').text(coordinates_click);
}
}
If you want to try, please go to https://erik-edgren.nu/map. The code above is updated to the current code. Please see the my answer below.