通过单击 OSM 获取县

Getting county from click on OSM

是否可以通过单击 OSM 地图(仅限美国)根据坐标检测州和县?

我可以在Leaflet JS中使用点击事件来协调:

map.on('click', function(ev) {
    console.log(ev.latlng);
});

我也可以通过做一些事情来获取位置数据;就像这样:

map.on("click", function(ev) {
    var ln = ev.latlng["lng"],
        lt = ev.latlng["lat"];
        pt = "https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat="+lt+"&lon="+ln;                       
});

return json 数据如下所示:

https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=28.964162684075685&lon=-98.29776763916017

但我似乎无法弄清楚下一步该做什么...如何从中获取县和州的值?

您可以直接从 jquery 获取 Ajax 或使用 axios。

let config = {
  minZoom: 2,
  maxZoom: 18,
};

const zoom = 5;
const lat = 28.964162684075685;
const lng = -98.29776763916017;

const map = L.map("map", config).setView([lat, lng], zoom);

L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
  attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
}).addTo(map);

map.on("click", function(e) {
  const { lat, lng } = e.latlng;

  const api = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}&zoom=18&addressdetails=1`;

  fetchData(api).then((data) => {
    const { county, state } = data.address;
    console.log(county, state);
  });
});

async function fetchData(url) {
  try {
    const response = await fetch(url);
    const data = await response.json();
    return data;
  } catch (err) {
    console.error(err);
  }
}
*,
:after,
:before {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

html {
  height: 100%;
}

body,
html,
#map {
  width: 100%;
  height: 100%;
}

body {
  position: relative;
  min-height: 100%;
  margin: 0;
  padding: 0;
  background-color: #f1f1f1;
}
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<link href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" rel="stylesheet" />
<div id="map"></div>