reactjs - 无法使用 ReactJS 在 OpenLayers 中的两个位置之间绘制默认线
问题描述
我正在尝试在 OpenLayers 和 ReactJS 的帮助下使用位置纬度和经度在两个位置(位置 A、位置 B)之间绘制一些默认线。但是没有绘制默认线。不幸的是,我找不到根本原因。我该如何解决这个问题?
代码:
componentDidMount() {
var map;
var raster=new Tile({
source: new OSM()
});
//Location A - Latitude and Longitude
var iconFeature1 =new Feature({
geometry: new Point(proj.transform([79.2652587890625,19.532871485421026], 'EPSG:4326', 'EPSG:3857')),
name: 'Marker 1' });
//Location B - Latitude and Longitude
var iconFeature2 =new Feature({
geometry: new Point(proj.transform([81.24279785156249,18.02679570052561], 'EPSG:4326', 'EPSG:3857')),
name: 'Marker 2' });
var source = new SourceVector({
features: [iconFeature1,iconFeature2],
wrapX: false
});
var vector = new LayerVector({
source: source,
style: new Style({
fill: new Fill({
color: 'white'
}),
stroke: new Stroke({
color: 'red'
})
})
});
map = new Map({
target: 'map',
layers: [raster,vector],
view: new View({
center: proj.fromLonLat([78.8718, 21.7679]),
zoom: 4
})
})
//To draw Line
var draw = new Draw({
source: source,
type: "LineString"
});
map.addInteraction(draw);
});
解决方案
您的主要问题是创建两个点但不创建线的事实。这就是我用下面的代码演示的。
它在您的特定上下文(例如 React)之外完成工作,但原则保持不变(您只需要更改命名空间)
转到http://openlayers.org/en/v4.6.5/examples/simple.html
打开浏览器调试器控制台并粘贴以下内容
// Location A - Latitude and Longitude
var coords1 = ol.proj.fromLonLat([79.2652587890625,19.532871485421026]);
var iconFeature1 =new ol.Feature({
geometry: new ol.geom.Point(coords1),
name: 'Marker 1'
});
// Location B - Latitude and Longitude
var coords2 = ol.proj.fromLonLat([81.24279785156249,18.02679570052561]);
var iconFeature2 =new ol.Feature({
geometry: new ol.geom.Point(coords2),
name: 'Marker 2'
});
var lineBetweenTwoFeatures =new ol.Feature({
geometry: new ol.geom.LineString([coords1, coords2]),
name: 'Line between markers'
});
// I add the 2 markers and the linestring
// between the two in the same source
// You may need to separate them in two sources
// depending of your use case
var source = new ol.source.Vector({
features: [iconFeature1, iconFeature2, lineBetweenTwoFeatures],
wrapX: false
});
var width = 3;
vector = new ol.layer.Vector({
source: source,
style: [
new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'white',
width: width + 2
})
}),
new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width: width
})
})
]
});
map.addLayer(vector);
map.getView().fit(source.getExtent());
重要的部分在lineBetweenTwoFeatures
你会得到以下结果
推荐阅读
- c - Linux内核模块编程中_do_fork()的问题
- c# - 统一对象位置
- android - 使用 Android Studio 评估 Android 应用启动时间?
- mysql - MySQL 转换表模式,同时将数据保持在新结构中(你见过的最佳模式)
- azure-cosmosdb - 以编程方式遍历多个顶点时使用顶点属性值创建边
- azure-cosmosdb - Cosmos DB 查询特定文档的子部分
- node.js - 用玩笑在模拟的 readline 模块的回调中做断言
- python - 无法使用 Anaconda 4.5 Python 3.6.6 导入 cv2
- python - 类变量和静态方法
- php - PHP - 跨来自同一访问者的多个 HTTP 请求编译请求(保持活动状态)并在达到某个阈值时执行?