Skip to content

Instantly share code, notes, and snippets.

@mbohun
Created November 12, 2024 00:46
Show Gist options
  • Save mbohun/d0679fc471b07af1df1323cb82cd836b to your computer and use it in GitHub Desktop.
Save mbohun/d0679fc471b07af1df1323cb82cd836b to your computer and use it in GitHub Desktop.
GIS Leaflet JavaScript GeoJSON
<html>
<head>
<base target="_top">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>map test</title>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<style>
html, body {
height: 100%;
margin: 0;
}
.leaflet-container {
height: 600px;
width: 800px;
max-width: 100%;
max-height: 100%;
}
</style>
</head>
<body style="background-color:#000000">
<div id="map" style="width: 100%; height: 100%;"></div>
<script>
const url = new URL(window.location.href);
const geojson_file = url.searchParams.get("geojson") ? url.searchParams.get("geojson") : "album.geojson";
console.log("GEOJSON: %s", geojson_file);
// NOTE: For now just extract the first coordinate from the GEOJSON file to setView()
function geojsonGetViewCoords(geojson) {
const geometry = geojson.features[0].geometry;
if ("Point" === geometry.type) {
return geometry.coordinates;
}
if ("Polygon" === geometry.type) {
return geometry.coordinates[0][0];
}
return [0.0, 0.0];
}
window.fetch(geojson_file).then(response => response.json()).then(geojson => {
const view_coords = geojsonGetViewCoords(geojson);
console.log(view_coords);
const max_zoom = 19;
const map = L.map('map').setView([view_coords[1], view_coords[0]], max_zoom);
L.control.scale().addTo(map);
const tiles = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: max_zoom,
attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}).addTo(map);
// TODO: write diff popup handlers for each geometry type Point, Polygon, etc.
function onEachFeature(feature, layer) {
if (feature.properties.photo) {
layer.bindPopup(`<img src="thumbs/${feature.properties.photo}"></img><p/>[${feature.geometry.coordinates}]`);
}
}
L.geoJSON(geojson, {onEachFeature: onEachFeature}).addTo(map);
});
</script>
</body>
</html>
@mbohun
Copy link
Author

mbohun commented Nov 12, 2024

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