Integrating Standard Map Controls in OpenLayers
Standard UI components for spatial mapping applications include zoom mechanisms, extent navigation, cursor tracking, scale indicators, overview panels, and fullscreen toggles. These elements can be attached to a map instance dynamically after initialization or declared during the map's initial configuration.
Controls can be instantiated and appended individually using the map's addControl method:
// Zoom Slider
const zoomSliderWidget = new ol.control.ZoomSlider();
mapInstance.addControl(zoomSliderWidget);
// Extent Navigation
const navToExtentWidget = new ol.control.ZoomToExtent({
extent: [13100000, 4290000, 13200000, 5210000]
});
mapInstance.addControl(navToExtentWidget);
// Cursor Coordinate Tracker
const cursorCoordCtrl = new ol.control.MousePosition({
coordinateFormat: ol.coordinate.createStringXY(4),
projection: 'EPSG:4326',
target: 'cursor-coords-display',
undefinedHTML: ' '
});
mapInstance.addControl(cursorCoordCtrl);
// Metric Scale Bar
const metricScaleCtrl = new ol.control.ScaleLine({
units: 'metric'
});
mapInstance.addControl(metricScaleCtrl);
// Overview Panel
const overviewPanelCtrl = new ol.control.OverviewMap({
className: 'ol-overviewmap ol-custom-overview',
layers: [
new ol.layer.Tile({
name: "BaseVectorLayer",
source: new ol.source.XYZ({
url: "http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=" + 'YOUR_TOKEN',
wrapX: false
})
}),
new ol.layer.Tile({
name: "BaseVectorAnnotation",
source: new ol.source.XYZ({
url: "http://t0.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=" + 'YOUR_TOKEN'
})
})
],
view: new ol.View({
projection: 'EPSG:3857'
}),
collapseLabel: '\u00BB',
label: '\u00AB',
collapsed: false
});
mapInstance.addControl(overviewPanelCtrl);
// Fullscreen Mode
const fullWindowCtrl = new ol.control.FullScreen();
mapInstance.addControl(fullWindowCtrl);Alternatively, instead of invoking addControl() multiple times, all custom controls can be grouped and injected directly into the map's configuration object via the controls property:
const mapInstance = new ol.Map({
layers: [
baseVectorLayer
],
target: 'map-container',
view: new ol.View({
zoom: 10
}),
interactions: new ol.interaction.defaults({
doubleClickZoom: false
}),
loadTilesWhileAnimating: true,
controls: ol.control.defaults().extend([
zoomSliderWidget,
navToExtentWidget,
cursorCoordCtrl,
metricScaleCtrl,
overviewPanelCtrl,
fullWindowCtrl
])
});