如何在openlayers中的点之间添加线

how to add lines between point in openlayers

我正在尝试在地图上的两点之间添加一条线。我有以下代码,但网页只显示了一张没有我想要的线的底图。

如何将这条线添加到 OpenLayers 地图?

  var map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      })
    ],
    view: new ol.View({
      center: ol.proj.fromLonLat([ -95.36,29.75]),
      zoom: 10
    })
  });
    var coords = [[-95.36,29.75], [-96.36,30.75]];
    var lineString = new ol.geom.LineString(coords);
    // transform to EPSG:3857
    lineString.transform('EPSG:4326', 'EPSG:3857');

    // create the feature
    var feature = new ol.Feature({
        geometry: lineString,
        name: 'Line'
    });

    var lineStyle = new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: '#ffcc33',
            width: 10
        })
    });

    var raster = new ol.layer.Tile({
      source: new ol.source.MapQuest({layer: 'sat'})
    });
    var source = new ol.source.Vector({
        features: [feature]
    });
    var vector = new ol.layer.Vector({
        source: source,
        style: [lineStyle]
    });
    map.addLayer(vector);
</script>

`

您的代码在 OpenLayers v5.x(和 v4.6.5,未出现在 v3.16.0 中)中包含 javascript 错误:

Uncaught TypeError: ol.source.MapQuest is not a constructor

删除指定的代码:

var raster = new ol.layer.Tile({
  source: new ol.source.MapQuest({layer: 'sat'})
});

并显示该行。

proof of concept fiddle

代码片段:

var map = new ol.Map({
  target: 'map',
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    })
  ],
  view: new ol.View({
    center: ol.proj.fromLonLat([-95.36, 29.75]),
    zoom: 10
  })
});
var coords = [
  [-95.36, 29.75],
  [-96.36, 30.75]
];
var lineString = new ol.geom.LineString(coords);
// transform to EPSG:3857
lineString.transform('EPSG:4326', 'EPSG:3857');

// create the feature
var feature = new ol.Feature({
  geometry: lineString,
  name: 'Line'
});

var lineStyle = new ol.style.Style({
  stroke: new ol.style.Stroke({
    color: '#ffcc33',
    width: 10
  })
});

var source = new ol.source.Vector({
  features: [feature]
});
var vector = new ol.layer.Vector({
  source: source,
  style: [lineStyle]
});
map.addLayer(vector);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px;
}
<link rel="stylesheet" href="https://openlayers.org/en/v5.2.0/css/ol.css" type="text/css">
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.2.0/build/ol.js"></script>
<div id="map" class="map"></div>