文章目录
- EPSG:4326
- Geographic Editing(地理要素编辑)
- Custom Interactions
- Earthquake Clusters
EPSG:4326
- 创建单位为度的比例尺
- 将视图的坐标系统设置为EPSG:4326(默认是EPSG:3857——Web 墨卡托投影)
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import {defaults as defaultControls, ScaleLine} from 'ol/control';
import TileLayer from 'ol/layer/Tile';
import TileWMS from 'ol/source/TileWMS';
var layers = [
new TileLayer({
source: new TileWMS({
url: 'https://ahocevar.com/geoserver/wms',
params: {
'LAYERS': 'ne:NE1_HR_LC_SR_W_DR',
'TILED': true
}
})
})
];
var map = new Map({
controls: defaultControls().extend([
new ScaleLine({
units: 'degrees'
})
]),
layers: layers,
target: 'map',
view: new View({
projection: 'EPSG:4326',
center: [0, 0],
zoom: 2
})
});
Geographic Editing(地理要素编辑)

- useGeographic在’ol/proj’模块中调用该函数可以使地图视图使用地理坐标(即使视图投影不是地理坐标)。
- 4个交互:select、modify、draw、snap
- 绘制要素时使用到的交互:draw、snap
- 修改要素时使用到的交互:select、modify、snap
import 'ol/ol.css';
import {Map, View} from 'ol/index';
import GeoJSON from 'ol/format/GeoJSON';
import {Modify, Select, Draw, Snap} from 'ol/interaction';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
import {OSM, Vector as VectorSource} from 'ol/source';
import {useGeographic} from 'ol/proj';
useGeographic();
var source = new VectorSource({
url: require('./data/geojson/countries.geojson'),
format: new GeoJSON()
});
var map = new Map({
target: 'map',
layers: [
new TileLayer({
source: new OSM()
}),
new VectorLayer({
source: source
})
],
view: new View({
center: [0, 0],
zoom: 2
})
});
var select = new Select();
var modify = new Modify({
features: select.getFeatures()
});
var draw = new Draw({
type: 'Polygon',
source: source
});
var snap = new Snap({
source: source
});
function removeInteractions() {
map.removeInteraction(modify);
map.removeInteraction(select);
map.removeInteraction(draw);
map.removeInteraction(select);
}
var mode = document.getElementById('mode');
function onChange() {
removeInteractions();
switch (mode.value) {
case 'draw': {
map.addInteraction(draw);
map.addInteraction(snap);
break;
}
case 'modify': {
map.addInteraction(select);
map.addInteraction(modify);
map.addInteraction(snap);
break;
}
default: {
}
}
}
mode.addEventListener('change', onChange);
onChange();
Custom Interactions
- 自定义交互,在call方法中声明交互涉及到的鼠标事件。
import 'ol/ol.css';
import Feature from 'ol/Feature';
import Map from 'ol/Map';
import View from 'ol/View';
import {
LineString,
Point,
Polygon
} from 'ol/geom';
import {
defaults as defaultInteractions,
Pointer as PointerInteraction
} from 'ol/interaction';
import {
Tile as TileLayer,
Vector as VectorLayer
} from 'ol/layer';
import {
TileJSON,
Vector as VectorSource
} from 'ol/source';
import {
Fill,
Icon,
Stroke,
Style
} from 'ol/style';
var Drag = (function (PointerInteraction) {
function Drag() {
PointerInteraction.call(this, {
handleDownEvent: handleDownEvent,
handleDragEvent: handleDragEvent,
handleMoveEvent: handleMoveEvent,
handleUpEvent: handleUpEvent
});
this.coordinate_ = null;
this.cursor_ = 'pointer';
this.feature_ = null;
this.previousCursor_ = undefined;
}
if (PointerInteraction) Drag.__proto__ = PointerInteraction;
Drag.prototype = Object.create(PointerInteraction && PointerInteraction.prototype);
Drag.prototype.constructor = Drag;
return Drag;
}(PointerInteraction));
function handleDownEvent(evt) {
var map = evt.map;
var feature = map.forEachFeatureAtPixel(evt.pixel,
function (feature) {
return feature;
});
if (feature) {
this.coordinate_ = evt.coordinate;
this.feature_ = feature;
}
return !!feature;
}
function handleDragEvent(evt) {
var deltaX = evt.coordinate[0] - this.coordinate_[0];
var deltaY = evt.coordinate[1] - this.coordinate_[1];
var geometry = this.feature_.getGeometry();
geometry.translate(deltaX, deltaY);
this.coordinate_[0] = evt.coordinate[0];
this.coordinate_[1] = evt.coordinate[1];
}
function handleMoveEvent(evt) {
if (this.cursor_) {
var map = evt.map;
var feature = map.forEachFeatureAtPixel(evt.pixel,
function (feature) {
return feature;
});
var element = evt.map.getTargetElement();
if (feature) {
if (element.style.cursor != this.cursor_) {
this.previousCursor_ = element.style.cursor;
element.style.cursor = this.cursor_;
}
} else if (this.previousCursor_ !== undefined) {
element.style.cursor = this.previousCursor_;
this.previousCursor_ = undefined;
}
}
}
function handleUpEvent() {
this.coordinate_ = null;
this.feature_ = null;
return false;
}
var pointFeature = new Feature(new Point([0, 0]));
var lineFeature = new Feature(
new LineString([
[-1e7, 1e6],
[-1e6, 3e6]
]));
var polygonFeature = new Feature(
new Polygon([
[
[-3e6, -1e6],
[-3e6, 1e6],
[-1e6, 1e6],
[-1e6, -1e6],
[-3e6, -1e6]
]
]));
var key = '您的mapbox的key';
var map = new Map({
interactions: defaultInteractions().extend([new Drag()]),
layers: [
new TileLayer({
source: new TileJSON({
url: 'https://a.tiles.mapbox.com/v4/aj.1x1-degrees.json?access_token=' + key
})
}),
new VectorLayer({
source: new VectorSource({
features: [pointFeature, lineFeature, polygonFeature]
}),
style: new Style({
image: new Icon({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.95,
src: require('./data/icon.png')
}),
stroke: new Stroke({
width: 3,
color: [255, 0, 0, 1]
}),
fill: new Fill({
color: [0, 0, 255, 0.6]
})
})
})
],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2
})
});
Earthquake Clusters
- 创建初始的样式——五角星
- 根据分辨率设定聚合要素样式的半径
- 设置聚合要素与一般要素的样式
- 选中聚合要素时的样式
- 设置选中交互时的条件
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import {
createEmpty,
getWidth,
getHeight,
extend
} from 'ol/extent';
import KML from 'ol/format/KML';
import {
defaults as defaultInteractions,
Select
} from 'ol/interaction';
import {
Tile as TileLayer,
Vector as VectorLayer
} from 'ol/layer';
import {
Cluster,
Stamen,
Vector as VectorSource
} from 'ol/source';
import {
Circle as CircleStyle,
Fill,
RegularShape,
Stroke,
Style,
Text
} from 'ol/style';
var earthquakeFill = new Fill({
color: 'rgba(255, 153, 0, 0.8)'
});
var earthquakeStroke = new Stroke({
color: 'rgba(255, 204, 0, 0.2)',
width: 1
});
var textFill = new Fill({
color: '#fff'
});
var textStroke = new Stroke({
color: 'rgba(0, 0, 0, 0.6)',
width: 3
});
var invisibleFill = new Fill({
color: 'rgba(255, 255, 255, 0.01)'
});
function createEarthquakeStyle(feature) {
var name = feature.get('name');
var magnitude = parseFloat(name.substr(2));
var radius = 5 + 20 * (magnitude - 5);
return new Style({
geometry: feature.getGeometry(),
image: new RegularShape({
radius1: radius,
radius2: 3,
points: 5,
angle: Math.PI,
fill: earthquakeFill,
stroke: earthquakeStroke
})
});
}
var maxFeatureCount;
var vector = null;
var calculateClusterInfo = function (resolution) {
maxFeatureCount = 0;
var features = vector.getSource().getFeatures();
var feature, radius;
for (var i = features.length - 1; i >= 0; --i) {
feature = features[i];
var originalFeatures = feature.get('features');
var extent = createEmpty();
var j = (void 0),
jj = (void 0);
for (j = 0, jj = originalFeatures.length; j < jj; ++j) {
extend(extent, originalFeatures[j].getGeometry().getExtent());
}
maxFeatureCount = Math.max(maxFeatureCount, jj);
radius = 0.25 * (getWidth(extent) + getHeight(extent)) /
resolution;
feature.set('radius', radius);
}
console.log(maxFeatureCount);
};
var currentResolution;
function styleFunction(feature, resolution) {
if (resolution != currentResolution) {
calculateClusterInfo(resolution);
currentResolution = resolution;
}
var style;
var size = feature.get('features').length;
if (size > 1) {
style = new Style({
image: new CircleStyle({
radius: feature.get('radius'),
fill: new Fill({
color: [255, 153, 0, Math.min(0.8, 0.4 + (size / maxFeatureCount))]
})
}),
text: new Text({
text: size.toString(),
fill: textFill,
stroke: textStroke
})
});
} else {
var originalFeature = feature.get('features')[0];
style = createEarthquakeStyle(originalFeature);
}
return style;
}
function selectStyleFunction(feature) {
var styles = [new Style({
image: new CircleStyle({
radius: feature.get('radius'),
fill: invisibleFill
})
})];
var originalFeatures = feature.get('features');
var originalFeature;
for (var i = originalFeatures.length - 1; i >= 0; --i) {
originalFeature = originalFeatures[i];
styles.push(createEarthquakeStyle(originalFeature));
}
return styles;
}
vector = new VectorLayer({
source: new Cluster({
distance: 40,
source: new VectorSource({
url: require('./data/kml/2012_Earthquakes_Mag5.kml'),
format: new KML({
extractStyles: false
})
})
}),
style: styleFunction
});
var raster = new TileLayer({
source: new Stamen({
layer: 'toner'
})
});
var map = new Map({
layers: [raster, vector],
interactions: defaultInteractions().extend([new Select({
condition: function (evt) {
return evt.type == 'pointermove' ||
evt.type == 'singleclick';
},
style: selectStyleFunction
})]),
target: 'map',
view: new View({
center: [0, 0],
zoom: 2
})
});