gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:14:22 26 4
gpt4 key购买 nike

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

如何将这条线添加到 OpenLayers map ?

this is what i have now

  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

screenshot of resulting map

代码片段:

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>

关于javascript - 如何在openlayers中的点之间添加线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52241140/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com