Getting county from click on OSM

637 views Asked by At

Is it possible to detect state and county based on coordinates from a click on OSM map (US only)?

I can get the coordinated using click event in Leaflet JS:

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

I can also get location data by doing something l;like this:

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;                       
});

Which will return json data that looks like this:

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

But I can't seem to be able to figure out what to do next... How do I get the county and state values from it?

1

There are 1 answers

0
Grzegorz T. On BEST ANSWER

You can just fetch, Ajax from jquery or use 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/[email protected]/dist/leaflet.js"></script>
<link href="https://unpkg.com/[email protected]/dist/leaflet.css" rel="stylesheet" />
<div id="map"></div>