一、地图上添加线控件:
1、css:
div.olControlPanel
{
top: 0px;
left: 50px;
position: absolute;
}
.olControlPanel div
{
display: block;
width: 24px;
height: 24px;
margin: 5px;
background-color: white;
}
.olControlPanel .olControlMouseDefaultsItemActive
{
background-color: blue;
background-image: url("http://www.cnblogs.com/OpenLayers/theme/default/img/pan_on.png");
}
.olControlPanel .olControlMouseDefaultsItemInactive
{
background-color: orange;
background-image: url("http://www.cnblogs.com/OpenLayers/theme/default/img/pan_off.png");
}
.olControlPanel .olControlDrawFeatureItemActive
{
width: 24px;
height: 22px;
background-image: url("http://www.cnblogs.com/OpenLayers/theme/default/img/draw_line_on.png");
}
.olControlPanel .olControlDrawFeatureItemInactive
{
width: 24px;
height: 22px;
background-image: url("http://www.cnblogs.com/OpenLayers/theme/default/img/draw_line_off.png");
}
2、js:
function init(){
lineLayer = new OpenLayers.Layer.Vector("画线");
map.addLayer(lineLayer);
panel = new OpenLayers.Control.Panel();
panel.addControls([new OpenLayers.Control.MouseDefaults(),
new OpenLayers.Control.DrawFeature(lineLayer, OpenLayers.Handler.Path,
{ title: '画线' })]);
map.addControl(panel);
}
function toggleControl() {
panel.deactivate();
}
二、保存线经纬度:
function getData(){
var line = lineLayer;
var linelist;
var list, i, j;
if (line != null && line.features.length > 0) {
for (i = 0; i < line.features.length; i++) {
list = "";
if (line.features[i].geometry.CLASS_NAME == "OpenLayers.Geometry.LineString") {
list = line.features[i].geometry.components;
for (j = 0; j < list.length; j++) {
if (linelist == null || linelist == "") {
linelist = i + ":"; //记录第几条线的点
}
else {
linelist += i + ":"; //记录第几条线的点
}
linelist += list[j].x + ","; //记录经度
linelist += list[j].y + ","; //记录维度
linelist += j + ";"; //记录线的第几个点
}
linelist += "|";
}
}
}
}
三、根据经纬度绘制线:
function draw(){
if (drawlayer != null) {
map.removeLayer(drawlayer);
}
drawlayer = new OpenLayers.Layer.Vector("画图");
map.addLayer(drawlayer);
if (data != null && data.length > 0) {
var pointList = [];
var lineFeature;
for (var i = 0; i < data.length; i++) {
var ll = new OpenLayers.LonLat(data[i].Lon, data[i].Lat);
var newPoint = new OpenLayers.Geometry.Point(ll.lon, ll.lat);
pointList.push(newPoint);
}
lineFeature = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.LineString(pointList));
drawlayer.addFeatures([lineFeature]);
pointList.clear();
}