Use*_*018 2 javascript openlayers
我想在 OpenLayers (OL) 4 中的两个坐标之间画一条线。我一直在 Internet 上寻找文档,但其中大多数仅适用于 OL 2(example1、example2)或 3(example3)。
我从 OL 网站上拿了这个例子并添加了我自己的代码。在这种情况下,我使用的是 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>
Run Code Online (Sandbox Code Playgroud)
但是,该线不会出现在地图上。这是我的JS 小提琴。我的代码缺少什么?
您需要使用 ol.proj.fromLonLat
var lonlat = ol.proj.fromLonLat([33.8, 8.4]);
var location2 = ol.proj.fromLonLat([37.5, 8.0]);
Run Code Online (Sandbox Code Playgroud)
您还需要提供new ol.geom.LineString
一组点
new ol.geom.LineString([lonlat, location2])
Run Code Online (Sandbox Code Playgroud)
您可以查看我的衍生示例,其中包含基于您的 Js Fiddle的修复程序
归档时间: |
|
查看次数: |
3852 次 |
最近记录: |