[英]How to get the latest value of latitude and longitude with click marker in leaflet js?
I want to get the latitude and longitude by click marker on the map.我想通过单击 map 上的标记来获取纬度和经度。 Here it is my code: http://jsfiddle.net/estri012/2c6bz0ap/1/这是我的代码: 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/leaflet@1.6.0/dist/leaflet.css"
integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
crossorigin=""/>
<!--leaflet js after leaflet css-->
<script src="https://unpkg.com/leaflet@1.6.0/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 ='©: <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.当我点击 map 时,它会显示我点击的所有标记和所有纬度、经度值。 The problem is every single time I click the mouse on the map, the marker always pops up.问题是每次我在 map 上单击鼠标时,总是会弹出标记。 And when I click another position on the map, the last marker is still there.当我在 map 上单击另一个 position 时,最后一个标记仍然存在。 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?怎么做?
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;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.