import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import TileWMS from 'ol/source/TileWMS'; // Using TileWMS as a common TMS example, you might use XYZ or custom
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import Feature from 'ol/Feature';
import Polygon from 'ol/geom/Polygon';
import Style from 'ol/style/Style';
import Stroke from 'ol/style/Stroke';
import Fill from 'ol/style/Fill';
import { transformExtent } from 'ol/proj'; // For projection transformation
// --- Configuration ---
const PIXEL_SIZE = 1000; // The desired square box size in pixels (e.g., 1000x1000 pixels)
// Example TMS Layer (replace with your actual TMS details)
// If your TMS is an XYZ tile set, use ol/source/XYZ
// If it's WMS, use ol/source/TileWMS
// For a generic TMS, you might have to create a custom Tile source depending on its URL structure.
// For demonstration, let's use a public WMS as a stand-in for a TMS layer that uses BBOX for requests.
const tmsLayer = new TileLayer({
source: new TileWMS({
url: 'https://ows.terrestris.de/osm/service?', // Example public WMS
params: {
'LAYERS': 'OSM-WMS',
'TILED': true
},
// For TMS, you might need to specify projection and tileGrid depending on your server
// projection: 'EPSG:4326', // If your TMS is in lat/lon
// tileGrid: createXYZ({ maxZoom: 19 }) // Or createForProjection etc.
}),
properties: {
name: 'My TMS Layer'
}
});
// --- Setup OpenLayers Map ---
const map = new Map({
target: 'map',
layers: [
tmsLayer,
// You might add an OSM base layer for context if your TMS doesn't cover the whole world
// new TileLayer({ source: new OSM() })
],
view: new View({
center: [0, 0], // Initial center (e.g., [876935, 6088264] for somewhere in Europe)
zoom: 2,
projection: 'EPSG:3857' // The projection of your map's view (typically Web Mercator)
}),
});
// --- Vector Layer for the Dynamic Box ---
const boxSource = new VectorSource();
const boxLayer = new VectorLayer({
source: boxSource,
style: new Style({
stroke: new Stroke({
color: 'rgba(255, 0, 0, 1)', // Red border
width: 3,
}),
fill: new Fill({
color: 'rgba(255, 0, 0, 0.2)', // Semi-transparent red fill
}),
}),
});
map.addLayer(boxLayer);
// Create a single feature for the box (we'll update its geometry)
const boxFeature = new Feature();
boxSource.addFeature(boxFeature);
// --- Function to Update the Box Geometry ---
function updateBoxGeometry() {
const view = map.getView();
const center = view.getCenter();
const resolution = view.getResolution(); // Map units per pixel at current zoom
if (!center || resolution === undefined) {
// Map not fully initialized yet
return;
}
// Calculate the size of the box in map units
const mapUnits = PIXEL_SIZE * resolution;
// Calculate the coordinates for the square polygon centered on the map view
const minX = center[0] - mapUnits / 2;
const minY = center[1] - mapUnits / 2;
const maxX = center[0] + mapUnits / 2;
const maxY = center[1] + mapUnits / 2;
// Create the polygon coordinates
const coordinates = [
[
[minX, minY],
[minX, maxY],
[maxX, maxY],
[maxX, minY],
[minX, minY] // Close the polygon
]
];
boxFeature.setGeometry(new Polygon(coordinates));
}
// --- Event Listeners ---
// 1. Update the box geometry whenever the map is moved (panned or zoomed)
map.on('moveend', updateBoxGeometry);
// 2. Initial draw of the box after the map is rendered
// Use 'postrender' to ensure view dimensions are established
map.once('postrender', updateBoxGeometry);
// 3. "Get Current BBOX" button click handler
document.getElementById('getNextBBox').addEventListener('click', () => {
const geometry = boxFeature.getGeometry();
if (geometry) {
// Get the extent (bbox) in the map's current projection (e.g., EPSG:3857)
const extent3857 = geometry.getExtent();
// Transform the extent to EPSG:4326 (latitude/longitude)
// This is crucial if you want a standard geographic bounding box
const extent4326 = transformExtent(extent3857, 'EPSG:3857', 'EPSG:4326');
// Format the output
const bboxString = `
Min Lat: ${extent4326[1].toFixed(6)},
Min Lon: ${extent4326[0].toFixed(6)},
Max Lat: ${extent4326[3].toFixed(6)},
Max Lon: ${extent4326[2].toFixed(6)}
`;
const rawBBox = `[${extent4326[0].toFixed(6)}, ${extent4326[1].toFixed(6)}, ${extent4326[2].toFixed(6)}, ${extent4326[3].toFixed(6)}]`;
document.getElementById('bboxOutput').innerHTML = `
<p><strong>Current BBOX (EPSG:4326):</strong></p>
<p>${bboxString}</p>
<p>Raw (MinLon, MinLat, MaxLon, MaxLat): ${rawBBox}</p>
`;
console.log("Current BBOX (EPSG:4326):", extent4326);
} else {
document.getElementById('bboxOutput').innerText = 'No box geometry found.';
}
});
// Set a more interesting initial view for demonstration
map.getView().setCenter([876935, 6088264]); // Example: Near Berlin, Germany (in EPSG:3857)
map.getView().setZoom(7);