First night hacking

This commit is contained in:
Chandler Swift 2025-02-10 19:46:31 -06:00
parent 73f023d269
commit 754a0c425c
Signed by: chandlerswift
GPG key ID: A851D929D52FB93F
8 changed files with 209 additions and 0 deletions

1
.envrc Normal file
View file

@ -0,0 +1 @@
use nix;

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
data/

17
Makefile Normal file
View file

@ -0,0 +1,17 @@
.PHONY: all
all: data/sidewalks.json
data/raw.osm.pbf: data scripts/fetch_osm_data.sh
./scripts/fetch_osm_data.sh
data/sidewalks.unmin.json: data/raw.osm.pbf ./scripts/parse_sidewalks.py
./scripts/parse_sidewalks.py data/raw.osm.pbf > data/sidewalks.unmin.json
# data/sidewalks.json: data/sidewalks.unmin.json
# <data/sidewalks.unmin.json jq -c >data/sidewalks.json
data/sidewalks.json: data scripts/fetch_sidewalk_data.sh
./scripts/fetch_sidewalk_data.sh
data:
mkdir -p data

41
scripts/fetch_osm_data.sh Executable file
View file

@ -0,0 +1,41 @@
#!/usr/bin/env nix-shell
#! nix-shell -i bash --pure
#! nix-shell -p bash curl cacert jq
if [ $# -eq 2 ]; then
OUTPUT=$1
else
OUTPUT=data/raw.osm.pbf
fi
WAY_DATA=$(curl -s https://overpass-api.de/api/interpreter --data-urlencode 'data=[out:json];way["name"="Northern Arizona University"];out geom;')
# Extract coordinates from the response
COORDINATES=$(echo "$WAY_DATA" | jq '[.elements[] | select(.type == "way") | .geometry[] | [.lon, .lat]]')
echo $COORDINATES
# Ensure we have coordinates
if [ -z "$COORDINATES" ]; then
echo "Error: Could not find coordinates for NAU"
exit 1
fi
# Construct the GeoJSON payload
PAYLOAD=$(jq -n --argjson coords "$COORDINATES" '{
"Name": "none",
"RegionType": "geojson",
"RegionData": {
"type": "Polygon",
"coordinates": [$coords]
}
}')
# Send the request to the Slice API
UUID=$(curl -X POST https://slice.openstreetmap.us/api/ -H "Content-Type: application/json" -d "$PAYLOAD")
while ! [ $(curl https://slice.openstreetmap.us/api/$UUID | jq -r '.Complete') = 'true' ]; do
sleep 1
done
curl https://slice.openstreetmap.us/files/$UUID.osm.pbf -o $OUTPUT

7
scripts/fetch_sidewalk_data.sh Executable file
View file

@ -0,0 +1,7 @@
#!/usr/bin/env nix-shell
#! nix-shell -i bash --pure
#! nix-shell -p bash curl cacert
# TODO: process out extraneous data
curl -s https://overpass-api.de/api/interpreter --data-urlencode 'data=[out:json];{{geocodeArea:Northern Arizona University}}->.searchArea;(way["highway"="footway"](area.searchArea);way["highway"="cycleway"](area.searchArea););out geom;' -o data/sidewalks.json

52
scripts/parse_sidewalks.py Executable file
View file

@ -0,0 +1,52 @@
#!/usr/bin/env nix-shell
#! nix-shell -i python
#! nix-shell -p python3 python3Packages.pyosmium python3Packages.requests
import osmium
import json
import sys
class SidewalkHandler(osmium.SimpleHandler):
def __init__(self):
super(SidewalkHandler, self).__init__()
self.sidewalks = []
def way(self, w):
# Convert OSM tags to a normal dict for easier use
tags = dict(w.tags)
is_sidewalk = False
# Check for a dedicated footway sidewalk
if tags.get('highway') == 'footway':
is_sidewalk = True
# # Alternatively, check if the 'sidewalk' tag is present and not set to no/none
# elif 'sidewalk' in tags and tags['sidewalk'].lower() not in ['no', 'none']:
# is_sidewalk = True
if is_sidewalk:
sidewalk = {
"id": w.id,
"nodes": [],
"tags": tags
}
# Gather node coordinates if available
for n in w.nodes:
# Ensure the node location is valid
if n.location.valid():
sidewalk["nodes"].append({
"lat": n.location.lat,
"lon": n.location.lon
})
self.sidewalks.append(sidewalk)
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.stderr.write("Usage: python script.py <path-to-osm-pbf-file>\n")
sys.exit(1)
pbf_file = sys.argv[1]
handler = SidewalkHandler()
# The locations=True flag makes sure node coordinates are available.
handler.apply_file(pbf_file, locations=True)
# Output the results as an indented JSON list
print(json.dumps(handler.sidewalks, indent=2))

8
shell.nix Normal file
View file

@ -0,0 +1,8 @@
let
pkgs = import <nixpkgs> {};
in
pkgs.mkShellNoCC {
packages = with pkgs; [
gnumake
];
}

82
test.html Normal file
View file

@ -0,0 +1,82 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Leaflet OSM Ways</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<style>
#map {
height: 100vh;
width: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
// Initialize the map
const map = L.map('map').setView([35.1927479, -111.6538784], 15);
// Set up the OpenStreetMap tile layer
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);
// Function to generate a random color
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
// Fetch OSM data
fetch('data/sidewalks.min.json')
.then(response => response.json())
.then(osmData => {
// Function to create the polyline and popup for each OSM way
osmData.forEach(way => {
const latlngs = way.nodes.map(node => [node.lat, node.lon]);
const color = getRandomColor(); // Generate a random color
const polyline = L.polyline(latlngs, {
color: color,
weight: 5,
opacity: 0.7
}).addTo(map);
polyline.on('mouseover', function(e) {
e.target.setStyle({
weight: 10,
opacity: 1,
});
});
polyline.on('mouseout', function(e){
e.target.setStyle({
weight: 5,
opacity: 0.7,
});
});
// Create a popup with the tags when clicking on the polyline
const tagsContent = Object.entries(way.tags).map(([key, value]) => {
return `<b>${key}:</b> ${value}`;
}).join('<br>');
polyline.bindPopup(tagsContent);
});
})
.catch(error => {
console.error('Error loading OSM data:', error);
});
</script>
</body>
</html>