Skip to content

Instantly share code, notes, and snippets.

@nxvhm
Created July 16, 2020 09:58
Show Gist options
  • Save nxvhm/0244f6096d20f47cf67fa60456285d84 to your computer and use it in GitHub Desktop.
Save nxvhm/0244f6096d20f47cf67fa60456285d84 to your computer and use it in GitHub Desktop.
Replace tiles set with the default openstreetmap tiles , download openstreet map tiles
<?php
# Folder in which current tiles reside
$currentTilesFolder = 'tiles';
# Timeout between requests so script doesnt get blocked
$timeout = 1;
# Init recusrive iterator
$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($currentTilesFolder));
$files = array();
# Get only file paths, no folders
foreach ($rii as $file) {
if ($file->isDir()){
continue;
}
$files[] = $file->getPathname();
}
// Url format https://a.tile.openstreetmap.org/${z}/${x}/${y}.png;
$downloadUrlPattern = 'https://a.tile.openstreetmap.org/%s/%s/%s';
# Make urself look like a browser
$forge = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" // i.e. An iPad
)
);
$context = stream_context_create($forge);
foreach ($files as $key => $pathName) {
# Remove current folder name from path to get clean tile path
$pathName = str_replace($currentTilesFolder, '', $pathName);
$parts = explode('\\', $pathName);
# echo $pathName . " \n";
$parts = array_values(array_filter($parts));
# print_r($parts);
list($z, $x, $y) = $parts;
$downloadUrl = sprintf($downloadUrlPattern, $z, $x, $y);
$newPath = "cool-tiles/$z/$x/";
if (!file_exists($newPath)) {
mkdir($newPath, 0777, true);
}
$newPath = $newPath.$y;
if (!file_exists($newPath)) {
$newTileContents = file_get_contents($downloadUrl, false, $context);
file_put_contents($newPath, $newTileContents);
echo $key . " For url: $downloadUrl new path is: $newPath \n";
sleep(1);
} else {
echo $key . ' '. $newPath . " already downloaded \n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment