I have this code generated by an app to report the GPS coordinates of a pin click back to the app. However, it leaves a pin wherever the user clicks. For the app, that is not a problem – it can simply take the most recent click and discard whatever came before. But on the map, it looks ugly and confusing, to leave a trail of breadcrumbs like that. I invented code to remove a pin when the user clicks directly on the pin – that was easy. But what I would like is for a click ANYWHERE on the map to remove the previous pin, if there is a previous pin. I know f*-all about Javascript, so I’m having trouble figuring out how to locate and remove the previous pin. Can someone please point me in the right direction?
I thought the variable elementID stores the last pin, but nothing I’ve tried with it has worked. Some experiments have made the click to create a new pin stop working altogether, but nothing has removed the old pin.
<!DOCTYPE html>
<html lang='en'>
<!-- saved from url=(0016)http://localhost -->
<head>
<base target='_top'>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>Vobor bodu</title>
<link rel='shortcut icon' type='image/x-icon' href='docs/images/favicon.ico'/>
<link rel='stylesheet' href='https://unpkg.com/leaflet@1.9.4/dist/leaflet.css' integrity='sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=' crossorigin=''/>
<script src='https://unpkg.com/leaflet@1.9.4/dist/leaflet.js' integrity='sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=' crossorigin=''></script>
<style>html, body {height: 100%; margin: 0;}</style>
</head>
<body>
<div id='map' style='width: 100%; height: 100%;'></div>
<p id = 'demo' style='display:none'>Mike</p>
<script>
const map=L.map('map').setView([49.6388864, 15.6005139], 8);
const tiles=L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {maxZoom: 19}).addTo(map);
var elementID = 'fred';
function onMapClick(e) {
// This is what I need to have happen, but I'm obviously doing it wrong.
elementID.remove;
document.getElementById('demo').innerHTML = e.latlng;
elementID=L.marker(e.latlng).addTo(map).bindPopup('New pin ' + e.latlng);
}
map.on('click', onMapClick);
</script>
</body>
</html>