现在有这么一个需求,当移动地图时,需要获取当前地图范围属于那个城市。如果频繁移动地图,会不停的调用接口获取当前地图视图所属城市,所以加个防抖,减少请求。代码示例:
<!DOCTYPE html>
<html>
<head>
<title>map</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"></script>
<style>
html,
body {
height: 100%;
width: 100%;
overflow: hidden;
}
#map {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="map">
</div>
</body>
<script>
var map = L.map('map', {
center: [31.243713, 121.509806],
zoom: 13
});
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© <a href="OpenStreetMaphttps://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(map);
//监测地图移动,也可以用其他地图状态变更事件 movestart、moveend
map.on('move', this.debounce((e) => this.onMove(e), 500));
function onMove(e) {
let latlng = map.getCenter();
//高德地图 逆地理编码(需申请个人开发key)
fetch(`https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=${(latlng.lng).toFixed(6)},${(latlng.lat).toFixed(6)}&key=你的key&radius=1000&extensions=all`).then(res => res.json()).then(json => {
console.log(json.regeocode.addressComponent);
})
}
//防抖
function debounce(fn, delay = 500) {
let timer = null;
return function () {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, arguments)
timer = null
}, delay)
}
}
</script>
</html>
逆地理编码接口返回数据