我想在 OpenLayers (OL) 4 中的两个坐标之间画一条线。我一直在 Internet 上寻找文档,但大多数文档仅适用于 OL 2(example1、example2)或 3(example3)。
我从OL网站上取了example,加上自己的代码。在这种情况下,我使用的是 LineString:
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.4/ol.css" type="text/css">
<style>
.map {
height: 400px;
width: 100%;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.4/ol.js"/>
<title>OpenLayers example</title>
</head>
<body>
<h2>My Map</h2>
<div id="map" class="map"/>
<script type="text/javascript">
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([37.41, 8.82]),
zoom: 5
})
});
//example coordinates
var lonlat = [33.8, 8.4];
var location2 = [37.5, 8.0];
//create the line's style
var linieStyle = [
// linestring
new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#d12710',
width: 2
})
})
];
//create the line
var linie = new ol.layer.Vector({
source: new ol.source.Vector({
features: [new ol.Feature({
geometry: new ol.geom.LineString(lonlat, location2),
name: 'Line',
})]
})
});
//set the style and add to layer
linie.setStyle(linieStyle);
map.addLayer(linie);
</script>
</body>
</html>
但是,这条线并没有出现在 map 上。 这是我的 JS Fiddle 。我的代码缺少什么?
最佳答案
您需要使用 ol.proj.fromLonLat
转换您的坐标
var lonlat = ol.proj.fromLonLat([33.8, 8.4]);
var location2 = ol.proj.fromLonLat([37.5, 8.0]);
您还需要提供 new ol.geom.LineString
点数组
new ol.geom.LineString([lonlat, location2])
可以看到my derived example with the fixes基于你的 Js Fiddle
关于javascript - 在 OpenLayers 4 中的两个坐标之间画一条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51301657/