0
votes

I want to get the latitude and longitude by click marker on the map. Here it is my code: http://jsfiddle.net/estri012/2c6bz0ap/1/

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <!-- leaflet css -->
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
    integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
    crossorigin=""/>
    <!--leaflet js after leaflet css-->
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
    integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
    crossorigin=""></script>
    <title>Fetch JSON from API</title>
</head>
<body>
    <h1>Letak Node 1</h1>

    <p>
        latitude: <span id="lat"></span><br />
        longitude: <span id="lon"></span>
    </p>
    <style>
        #node1Map { height: 260px; }
      </style>
      <div id="node1Map"></div>
    <script>
    const mymap = L.map('node1Map').setView([0, 0], 1);
    const attribution ='&copy: <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors';

    const tileUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
    const tiles = L.tileLayer(tileUrl, { attribution });
    tiles.addTo(mymap);

    // get coordinate
    var lat, lng;

    mymap.on('click', function(e) {
    lat = e.latlng.lat;
    lng = e.latlng.lng;
    console.log(lat);
    console.log(lng);
    L.marker([lat, lng]).addTo(mymap);
    document.getElementById('lat').textContent = lat;
    document.getElementById('lon').textContent = lng;
    });

    </script>
   </body>
   </html>

When I click on the map, it shows all markers and all the latitude, longitude values that I clicked. The problem is every single time I click the mouse on the map, the marker always pops up. And when I click another position on the map, the last marker is still there. I just want the marker to be pop up on the last time I click the mouse and get the last latitude, longitude from the last mouse click. How to do that?

1

1 Answers

1
votes

You can save your marker as a variable and then remove the old one before adding a new one.

// get coordinate
var lat, lng, marker;
mymap.on("click", function (e) {
  if (marker) mymap.removeLayer(marker);
  lat = e.latlng.lat;
  lng = e.latlng.lng;
  console.log(lat);
  console.log(lng);
  marker = L.marker([lat, lng]).addTo(mymap);
  document.getElementById("lat").textContent = lat;
  document.getElementById("lon").textContent = lng;
});