Javascript 在OpenLayers 4中的两个坐标之间绘制一条线
我想在OpenLayers(OL)4中的两个坐标之间画一条线。我一直在互联网上寻找文档,但大多数文档只针对OL 2(,)或3() 我从OL网站上获取了代码,并添加了自己的代码。在本例中,我使用的是LineString:Javascript 在OpenLayers 4中的两个坐标之间绘制一条线,javascript,openlayers,Javascript,Openlayers,我想在OpenLayers(OL)4中的两个坐标之间画一条线。我一直在互联网上寻找文档,但大多数文档只针对OL 2(,)或3() 我从OL网站上获取了代码,并添加了自己的代码。在本例中,我使用的是LineString: <!doctype html> <html lang="en"> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs
<!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>
.地图{
高度:400px;
宽度:100%;
}
OpenLayers示例
我的地图
var map=新ol.map({
目标:“地图”,
图层:[
新ol.layer.Tile({
来源:new ol.source.OSM()
})
],
视图:新ol.view({
中心:Lonlat的其他项目([37.41,8.82]),
缩放:5
})
});
//示例坐标
var lonlat=[33.8,8.4];
var位置2=[37.5,8.0];
//创建线条的样式
变量linieStyle=[
//线绳
新ol风格({
笔划:新的ol风格笔划({
颜色:“#d12710”,
宽度:2
})
})
];
//创建线
var linie=新的ol.layer.Vector({
来源:新ol.source.Vector({
功能:[新ol.功能({
几何图形:新的ol.geom.LineString(lonlat,位置2),
名称:'行',
})]
})
});
//设置样式并添加到图层
linie.setStyle(linieStyle);
图.添加层(linie);
但是,该线不会出现在地图上。
这是我的。我的代码缺少什么?您需要使用LONLAT的ol.proj.fromLonLat转换坐标
var lonlat=ol.proj.fromlont([33.8,8.4]);
var location2=来自Lonlat的其他项目([37.5,8.0]);
您还需要提供新的ol.geom.LineString
点数组
new ol.geom.LineString([lonlat,位置2])
你可以根据你的Js小提琴看到我想要的东西。谢谢