Core Concepts
OpenLayers is a powerful JavaScript library for creating enteractive maps in web applications. It supports various map sources, projections, and layers while providing extensive customization options.
Basic Implementation
<!-- Required CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@7.3.0/ol.css">
<style>
#map-container {
width: 600px;
height: 400px;
}
</style>
<div id="map-container"></div>
<!-- JavaScript implementation -->
<script src="https://cdn.jsdelivr.net/npm/ol@7.3.0/dist/ol.js">
const mapInstance = new ol.Map({
target: 'map-container',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
projection: 'EPSG:4326',
center: [114.064839, 22.548857],
zoom: 12
})
});
</script>
Map Configuration
Coordinate Systems
OpenLayers supports multiple coordinate reference systems:
EPSG:3857(Web Mercator) - DefaultEPSG:4326(WGS84) - Standard latitude/longitude
view: new ol.View({
projection: 'EPSG:4326',
center: [113.267252, 23.137949],
zoom: 11
})
View Settings
view: new ol.View({
center: [0, 0],
zoom: 2,
minZoom: 1,
maxZoom: 18,
rotation: Math.PI/4 // 45 degree rotation
})
Layer Management
Multiple Tile Sources
// Bing Maps example
new ol.layer.Tile({
source: new ol.source.BingMaps({
key: 'YOUR_API_KEY',
imagerySet: 'Aerial'
})
})
// Vector layer example
new ol.layer.Vector({
source: new ol.source.Vector({
format: new ol.format.GeoJSON(),
url: 'data/geojson.json'
})
})
Layer Controls
// Toggle layer visibility
function toggleLayer() {
const firstLayer = mapInstance.getLayers().item(0);
firstLayer.setVisible(!firstLayer.getVisible());
}
// Adjust layer opacity
function setLayerOpacity(value) {
mapInstance.getLayers().item(0).setOpacity(value);
}
Built-in Controls
Scale Control
const scaleControl = new ol.control.ScaleLine({
units: 'metric'
});
mapInstance.addControl(scaleControl);
Fullscreen Control
mapInstance.addControl(new ol.control.FullScreen());
Overview Map
mapInstance.addControl(new ol.control.OverviewMap({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
collapsed: false
}));
Zoom Controls
// Zoom to extent
mapInstance.addControl(new ol.control.ZoomToExtent({
extent: [minX, minY, maxX, maxY]
}));
// Zoom slider
mapInstance.addControl(new ol.control.ZoomSlider());