Skip to content

Instantly share code, notes, and snippets.

@mr-wolf-gb
Last active November 27, 2023 12:20
Show Gist options
  • Select an option

  • Save mr-wolf-gb/b0cb61d7165ac3cddbd1df465a3d594b to your computer and use it in GitHub Desktop.

Select an option

Save mr-wolf-gb/b0cb61d7165ac3cddbd1df465a3d594b to your computer and use it in GitHub Desktop.
leaflet openstreetmap proxy
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Storage;
class Controller extends BaseController
{
use AuthorizesRequests, ValidatesRequests;
function index() {
$initialMarkers = [
[
'position' => [
'lat' => 28.625485,
'lng' => 79.821091
],
'draggable' => true
],
[
'position' => [
'lat' => 28.625293,
'lng' => 79.817926
],
'draggable' => false
],
[
'position' => [
'lat' => 28.625182,
'lng' => 79.81464
],
'draggable' => true
]
];
return view('welcome', compact('initialMarkers'));
}
public function openstreetMap(Request $request, $s, $z, $x, $y)
{
$imageName = "$s-$z-$x-$y.png";
$client = new \GuzzleHttp\Client([
'verify' => false,
'http_errors' => false,
]);
//https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png
$response = $client->request('GET', "https://$s.tile.openstreetmap.org/$z/$x/$y.png");
$imageContent = $response->getBody()->getContents();
$mimeType = $response->getHeaderLine('Content-Type');
$fileSize = $response->getHeaderLine('Content-Length');
header('Content-Type: ' . $mimeType);
header('Content-Length: ' . $fileSize);
header('Content-Disposition: attachment; filename="'.$imageName.'"');
echo $imageContent;
}
}
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>
<!-- Fonts -->
<link rel="preconnect" href="https://fonts.bunny.net">
<link href="https://fonts.bunny.net/css?family=figtree:400,600&display=swap" rel="stylesheet" />
<style>
.text-center {
text-align: center;
}
#map {
width: '100%';
height: 400px;
}
</style>
<link rel='stylesheet' href='https://unpkg.com/leaflet@1.8.0/dist/leaflet.css' crossorigin='' />
</head>
<body class="antialiased">
<h1 class='text-center'>Laravel Leaflet Maps</h1>
<div id='map'></div>
<script src='https://unpkg.com/leaflet@1.8.0/dist/leaflet.js' crossorigin=''></script>
@php
$mapUrl = route('openstreetMap', ['s' => 's', 'z' => 'z', 'x' => 'x', 'y' => 'y']);
$mapUrl = str_replace('/s', '/{s}', $mapUrl);
$mapUrl = str_replace('/z', '/{z}', $mapUrl);
$mapUrl = str_replace('/x', '/{x}', $mapUrl);
$mapUrl = str_replace('/y', '/{y}', $mapUrl);
@endphp
<script>
let map, markers = [];
/* ----------------------------- Initialize Map ----------------------------- */
function initMap() {
map = L.map('map', {
center: {
lat: 28.626137,
lng: 79.821603,
},
zoom: 15
});
L.tileLayer("{{ $mapUrl }}", {
attribution: '© OpenStreetMap'
}).addTo(map);
map.on('click', mapClicked);
initMarkers();
}
initMap();
/* --------------------------- Initialize Markers --------------------------- */
function initMarkers() {
const initialMarkers = <?php echo json_encode($initialMarkers); ?>;
for (let index = 0; index < initialMarkers.length; index++) {
const data = initialMarkers[index];
const marker = generateMarker(data, index);
marker.addTo(map).bindPopup(`<b>${data.position.lat}, ${data.position.lng}</b>`);
map.panTo(data.position);
markers.push(marker)
}
}
function generateMarker(data, index) {
return L.marker(data.position, {
draggable: data.draggable
})
.on('click', (event) => markerClicked(event, index))
.on('dragend', (event) => markerDragEnd(event, index));
}
/* ------------------------- Handle Map Click Event ------------------------- */
function mapClicked($event) {
console.log(map);
console.log($event.latlng.lat, $event.latlng.lng);
}
/* ------------------------ Handle Marker Click Event ----------------------- */
function markerClicked($event, index) {
console.log(map);
console.log($event.latlng.lat, $event.latlng.lng);
}
/* ----------------------- Handle Marker DragEnd Event ---------------------- */
function markerDragEnd($event, index) {
console.log(map);
console.log($event.target.getLatLng());
}
</script>
</body>
</html>
@S-Marouene
Copy link

public function openstreetMap(Request $request, $s, $z, $x, $y)
    {
        $imageName = "$s-$z-$x-$y.png";
        $imagePath = public_path('openstreetmap/' . $imageName);
        if (!File::exists($imagePath)) {
            $client = new GuzzleHttpClient(['verify' => false, 'http_errors' => false]);
            $resp = $client->request('GET', "https://$s.tile.openstreetmap.org/$z/$x/$y.png");
            $pathDownload = public_path('/openstreetmap');
            if (!File::isDirectory($pathDownload)) {
                File::makeDirectory($pathDownload, 0777, true, true);
            }
            $imageContent = $resp->getBody()->getContents();
            $mimeType = $resp->getHeaderLine('Content-Type');
            $fileSize = $resp->getHeaderLine('Content-Length');
            File::put($imagePath, $imageContent);
        } else {
            $imageContent = File::get($imagePath);
            $mimeType = File::mimeType($imagePath);
            $fileSize = File::size($imagePath);
        }
        return response()->file($imagePath, ['Content-Type' => $mimeType, 'Content-Length' => $fileSize])
            ->setStatusCode(200)
            ->setCharset('utf-8')
            ->setContentDisposition('attachment')
            ->setVary('Accept-Encoding');
    }

@S-Marouene
Copy link

Route::get('{s}/openstreetMap/{z}/{x}/{y}', [Controller::class, 'openstreetMap'])->name('openstreetMap');
Route::get('/', [Controller::class, 'index'])->name('index');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment