I have openlayers map with tms layer, I have information related to the tms layer, I…
- User
I have openlayers map with tms layer, I have information related to the tms layer, I want to show a square box based on the pixel size 1000*1000 pixel, when user zoom in zoom out the window should adjust with the zoom and when clicked next get the bbox of the rectangle
Assistant
Here's a solution to create a 1000x1000 pixel box on your OpenLayers map that adjusts with zoom level and can return its bbox coordinates:
// Create a vector layer for the rectangle const vectorSource = new ol.source.Vector(); const vectorLayer = new ol.layer.Vector({ source: vectorSource, style: new ol.style.Style({ stroke: new ol.style.Stroke({ color: 'rgba(255, 0, 0, 1)', width: 2, }), fill: new ol.style.Fill({ color: 'rgba(255, 0, 0, 0.1)', }), }), }); // Add the vector layer to your existing map map.addLayer(vectorLayer); // Create a rectangle feature const rectangleFeature = new ol.Feature(); vectorSource.addFeature(rectangleFeature); // Function to update the rectangle based on current view function updateRectangle() { const view = map.getView(); const center = view.getCenter(); const resolution = view.getResolution(); // Calculate size for 1000x1000 pixel box const pixelSize = 1000; const width = resolution * pixelSize; const height = resolution * pixelSize; // Create rectangle coordinates const minX = center[0] - width / 2; const minY = center[1] - height / 2; const maxX = center[0] + width / 2; const maxY = center[1] + height / 2; // Create polygon geometry const rectangleGeom = new ol.geom.Polygon([ [ [minX, minY], [maxX, minY], [maxX, maxY], [minX, maxY], [minX, minY] ] ]); rectangleFeature.setGeometry(rectangleGeom); } // Update rectangle when view changes (zoom/pan) map.on('moveend', updateRectangle); updateRectangle(); // Initial update // Function to get bbox when "next" is clicked function getBoxBounds() { const geometry = rectangleFeature.getGeometry(); const extent = geometry.getExtent(); // [minX, minY, maxX, maxY] // Optional: Convert to geographic coordinates if needed const minCoord = ol.proj.transform([extent[0], extent[1]], map.getView().getProjection(), 'EPSG:4326'); const maxCoord = ol.proj.transform([extent[2], extent[3]], map.getView().getProjection(), 'EPSG:4326'); const bbox = { minX: minCoord[0], minY: minCoord[1], maxX: maxCoord[0], maxY: maxCoord[1] }; console.log('BBox:', bbox); return bbox; } // Add click handler for your "next" button document.getElementById('next-button').addEventListener('click', getBoxBounds);Would you like me to explain or break down the code?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.