【问题标题】:Getting county from click on OSM通过单击 OSM 获取县
【发布时间】:2022-01-04 06:43:02
【问题描述】:

是否可以通过单击 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;                       
});

这将返回如下所示的 json 数据:

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

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

【问题讨论】:

  • 我什么都不懂,但是在这个 json 中你显示的是 county: "Atascosa County"state: "Texas"
  • @GrzegorzT。数据在提名人的页面上返回。我实际上需要在变量中捕获县和州的名称,以便在其他函数中使用。
  • 你有下面的解决方案。

标签: leaflet openstreetmap


【解决方案1】:

您可以从 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>

【讨论】:

    猜你喜欢
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 2017-03-10
    • 2017-09-05
    • 1970-01-01
    • 2014-10-06
    相关资源
    最近更新 更多