Skip to content

Instantly share code, notes, and snippets.

@dave1010
Created January 8, 2024 12:53
Show Gist options
  • Save dave1010/b7a2ef9e0ddc2e6e7783be6f43d3a14b to your computer and use it in GitHub Desktop.
Save dave1010/b7a2ef9e0ddc2e6e7783be6f43d3a14b to your computer and use it in GitHub Desktop.
Get localities from OSM
<?php
// API details: https://wiki.openstreetmap.org/wiki/Overpass_API
// Define your bounding box [south latitude, west longitude, north latitude, east longitude]
$bbox = array(51.28, -0.489, 55.81, 1.76); // Example bounding box around London
// Construct the Overpass query
$query = "[out:json];(node[\"place\"=\"city\"](".implode(',', $bbox).");node[\"place\"=\"town\"](".implode(',', $bbox)."););out;";
// Initialize cURL session
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://overpass-api.de/api/interpreter");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "data=" . urlencode($query));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Execute cURL session
$response = curl_exec($ch);
curl_close($ch);
// Decode JSON response
$data = json_decode($response, true);
// Open a file in write mode
$fp = fopen('localities.csv', 'w');
fputcsv($fp, array('id', 'latitude', 'longitude', 'name'));
// Process data and write to CSV
foreach ($data['elements'] as $element) {
$id = $element['id'];
$lat = $element['lat'];
$lon = $element['lon'];
$name = isset($element['tags']['name']) ? $element['tags']['name'] : 'N/A';
fputcsv($fp, array($id, $lat, $lon, $name));
}
// Close the file
fclose($fp);
echo "CSV file created.\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment