这个例子是使用openlayers来绘制矢量点、圆、和polygon的。首先需要创建一个地图。如下的代码。注意这里接入的是osm地图,相应的设置地图飞至的中心点,缩放层级。
var flyPt= ol.proj.fromLonLat([106.671670,26.409000]);
map = new ol.Map({
target:'map',
//在地图容器中加载图层
layers:[
//加载瓦片图层数据
new ol.layer.Tile({
source: new ol.source.OSM() //加载OSM瓦片
})
],
//地图视图设置
view:new ol.View({
center:flyPt,
//projection: 'EPSG:4326',
zoom:11,
minZonm:10,
maxZoom:15,
rotation:0, //设置旋转角度
}),
});
下面我们来绘制一下点数据。
for(var i=0,len=arraylocal.length;i<len;i++){
var newFeature = new ol.Feature({
geometry: new ol.geom.Point(arraylocal[i]),
name: ''
});
//设置点的样式
newFeature.setStyle(createlabelstylefunction());
//将当前要素添加到矢量数据源中
vectorSource.addFeature(newFeature);
}
//相应的点样式
function createlabelstylefunction() {
//返回一个样式
return new ol.style.Style({
//把点的样式换成ICON图标
image: new ol.style.Icon({
//控制标注图片和文字之间的距离
anchor: [0.5, 0.5],
//标注样式的起点位置
anchorOrigin: 'top-right',
//X方向单位:分数
anchorXUnits: 'fraction',
//Y方向单位:像素
anchorYUnits: 'pixels',
//偏移起点位置的方向
offsetOrigin: 'top-right',
//透明度
opacity: 0.75,
offset:[0,0],
//图片路径
src: 'pic/mark.png'
}),
//文本样式
text: new ol.style.Text({
//对齐方式
textAlign: 'center',
//文本基线
textBaseline: 'middle',
//字体样式
font: 'normal 12px 微软雅黑',
//文本内容
text: feature.get('name'),
//填充样式
fill: new ol.style.Fill({
color: '#aa3300'
}),
//笔触
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
})
})
});
};
接下来是绘制圆的代码。
//画圆test
// 中心点 半径
var centerradius = new ol.geom.Circle([114.298353,30.623705],0.01);
centerradius = centerradius.clone().transform('EPSG:4326', 'EPSG:3857');
var circlefeature = new ol.Feature({
geometry:centerradius,
name: ''
});
circlefeature.setStyle(MyStyle(circlefeature));
vectorSource.addFeature(circlefeature);
//相应的圆的样式
function MyStyle() {
//返回一个样式
return new ol.style.Style({
fill:new ol.style.Fill({
color:'pink'
}),
stroke:new ol.style.Stroke({
color:'red',
width:3
})
});
};
最后我们来绘制一个多边形数据。
var polygon = "[[110, 39], [116, 39], [116, 33], [110, 33], [110, 39]]";
var polygonjson = JSON.parse(polygon);
var polygon = new ol.geom.Polygon([polygonjson]);
polygon.applyTransform(ol.proj.getTransform('EPSG:4326', 'EPSG:3857'));
var featuretest = new ol.Feature(polygon);
featuretest.setStyle(MyStyle());
vectorSource.addFeature(featuretest);
当然不要忘记了,要创建矢量图层,然后将数据添加到矢量图层中。
//初始化矢量图层
vectorLayer = new ol.layer.Vector({
//数据源
source:vectorSource
});
map.addLayer(vectorLayer);
好了,最后我们来看一下绘制的结果如下所示。