废话不多说,直接上代码吧。
//点
var pointFeature = new ol.Feature(new ol.geom.Point([0, 0]));
//线
var lineFeature = new ol.Feature(
new ol.geom.LineString([[-1e7, 1e6], [-1e6, 3e6]]));
//面
var polygonFeature = new ol.Feature(
new ol.geom.Polygon([[[-3e6, -1e6], [-3e6, 1e6],
[-1e6, 1e6], [-1e6, -1e6], [-3e6, -1e6]]]));
//也可以这样创建feature
//var geom=new ol.geom.Polygon([坐标数组]);
//var polygonFeature=new Feature({
// geomtery:geom
//})
//图层资源
var source=new ol.source.Vector({
features: [pointFeature, lineFeature, polygonFeature]
})
//也可以这样加载feature
//source.addFeaute(polygonFeature);
//图层
var layer=new ol.layer.Vector({
source:source
,style: new ol.style.Style({
image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.95,
src: 'https://openlayers.org/en/v3.19.1/examples/data/icon.png'
})),
stroke: new ol.style.Stroke({
width: 3,
color: [255, 0, 0, 1]
}),
fill: new ol.style.Fill({
color: [0, 0, 255, 0.6]
})
})
})
//也可以这样添加sourc
//map.addSource(source);
//地图
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.TileJSON({
url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure'
})
})
,layer
],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
//也可以这样加图层
//map.addLayer(layer);
//跳转到定区域
map.getView().fit(polygonFeature.getGeometry(),map.getSize());