javascript - OpenLayers:无法将坐标线串添加到地图
问题描述
我在显示基于现有坐标列表的线串时遇到问题,希望能得到一些帮助。下面是我的代码,它显示了一个 OpenLayers5 地图,但没有覆盖线串。
我已经阅读了许多不同的线程(OpenLayers 3:简单的 LineString 示例)和 API 文档,但我无法弄清楚我所缺少的内容。
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" type="text/css">
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<script type="text/javascript">
var view = new ol.View({
center: ol.proj.fromLonLat([10,50]),
zoom: 14
})
//Dummy coords
var coordinates = [
[10, 50],
[11, 51],
[12, 55]
];
var layerLines = new ol.layer.Vector({
source: new ol.source.Vector({
features: [new ol.Feature({
geometry: new ol.geom.LineString(coordinates),
name: 'Line'
})]
}),
style : new ol.style.Style({
stroke : new ol.style.Stroke({
strokeColor: '#ff0000',
strokeWidth: 5
})
})
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: view
});
map.addLayer(layerLines);
</script>
</body>
</html>
解决方案
两个错误。首先,它是width
和color
,不是strokeWidth/Color
。其次,您将中心从 lon/lat 重新投影到 WebMercator,但忘记对线坐标执行相同的操作 - 这样您的线实际上位于几内亚湾的某个地方(距离 0,0 点 10/50 米)。
这是更正的版本。
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css"
type="text/css">
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<script>
var view = new ol.View({
center: ol.proj.fromLonLat([10, 50]),
zoom: 14
})
//Dummy coords
var coordinates = [
ol.proj.fromLonLat([10, 50]),
ol.proj.fromLonLat([11, 51]),
ol.proj.fromLonLat([12, 55])
];
var layerLines = new ol.layer.Vector({
source: new ol.source.Vector({
features: [new ol.Feature({
geometry: new ol.geom.LineString(coordinates),
name: 'Line'
})]
}),
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#ff0000',
width: 3
})
})
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: view
});
map.addLayer(layerLines);
</script>
</body>
</html>
推荐阅读
- docker - python docker api 我们如何设置路径环境变量?
- html - 如何在不需要的地方移动锚元素
- php - 如何为指向我的服务器的域动态创建新的 LetsEncrypt/Certbot SSL 证书?
- linux - 在 Docker LCOW 上通过 qemu binfmt_misc 运行 linux/arm 容器
- python - Pandas 根据条件过滤行,但始终保留第一行
- r - R 版本的 Vlookup,每个单元格有多个匹配项
- python - 如果前一组中存在,则删除行
- java - 当我们想要使用 map.get(key).wait() 时,当值是 AtomicLong 时同步 map.get(key) 真的有意义吗?
- javascript - eslint 动态改变文件列表
- sqlite - 使用存储在变量中的索引位置选择 SQLite3 数据