我一直在看这个jsfiddle:http://jsfiddle.net/am15oq1r/
我试图修改它,以便我可以传递任意数量的点(而不是它用作示例的3)。
我的问题是,当我移动点时,加入点的lineString会消失。
如果有人在我出错的地方指出(没有双关语!),我会非常感激。
我基本上创建了一个包含点的数组,然后循环遍历数组以应用他们需要的任何操作。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="ol/ol3.js"></script>
<style type="text/css">
#map {
position: fixed;
top: 0em;
bottom: 0em;
left: 0em;
right: 0em;
}
</style>
<title></title>
</head>
<body>
<div id="map"></div>
<script type='text/javascript'>
var baseLayer = new ol.layer.Tile({ source: new ol.source.OSM() });
var aa = new ol.Feature({geometry: new ol.geom.Point([000000, 000000]), draggable: true});
var bb = new ol.Feature({geometry: new ol.geom.Point([000000, 100000]), draggable: true});
var cc = new ol.Feature({geometry: new ol.geom.Point([100000, 000000]), draggable: true});
var pointsArray = [aa, bb, cc];
var line = new ol.Feature(new ol.geom.LineString([]));
var defaultRoute = new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#008800',
width: 4
}),
fill: new ol.style.Fill({
color: 'rgba(255, 55, 55, 1)'
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: '#ff5555'
}),
stroke: new ol.style.Stroke({
color: '#000000',
width: 1
}),
})
});
line.setStyle(new ol.style.Style({
stroke: new ol.style.Stroke({color: 'red', width: 2}),
fill: new ol.style.Fill({color: 'red'})
}));
var vectorFeatures = [];
for (var i = 0; i < pointsArray.length; i++) {
pointsArray[i].setStyle(defaultRoute);
vectorFeatures.push(pointsArray[i]);
}
function updateRoute (event) {
var lsArray = [];
var lsCoords;
for (var i = 0; i < vectorFeatures.length; i++) {
lsCoords = vectorFeatures[i].getGeometry().getCoordinates();
lsArray.push(lsCoords);
}
var ls = new ol.geom.LineString(lsArray);
line.setGeometry(ls);
vectorFeatures.push(line);
}
updateRoute();
for (var i = 0; i < pointsArray.length; i++) {
pointsArray[i].on('change', updateRoute); //line disappears
//pointsArray[i].on('mousemove', updateRoute); //line does not move
}
var layer = new ol.layer.Vector({
source: new ol.source.Vector({ features: vectorFeatures }),
style: defaultRoute
});
console.info(layer);
var map = new ol.Map({
target: document.getElementById('map'),
layers: [baseLayer, layer],
view: new ol.View({center: [0, 0], zoom: 7})
});
var movingFeature = null;
map.on('pointerdown', function (event) {
var pixel = map.getEventPixel(event.originalEvent);
movingFeature = map.forEachFeatureAtPixel(pixel, function (feature) {
// console.info(feature);
return feature.get('draggable') ? feature : undefined;
});
event.preventDefault();
});
map.on('pointerup', function (event) {
movingFeature = null;
});
map.getTarget().addEventListener('mousemove', function (event) {
if (movingFeature) {
var coordinates = map.getEventCoordinate(event);
movingFeature.getGeometry().setCoordinates(coordinates);
}
});
</script>
</body>
</html>
提前致谢, 尼尔。