我的数据库中存在来自用户定义多边形的经度 - 纬度顶点。我的问题是:如何在地图上重新创建并显示它们?使用Google Maps API非常容易,但我找不到任何有关如何使用OpenLayers执行此操作的文档或示例。有没有人有这方面的经验?
答案 0 :(得分:36)
经过大量的实验,我发现了如何做到这一点:
var sitePoints = [];
var siteStyle = {
// style_definition
};
var epsg4326 = new OpenLayers.Projection("EPSG:4326");
for (var i in coordinates) {
var coord = coordinates[i];
var point = new OpenLayers.Geometry.Point(coord.lng, coord.lat);
// transform from WGS 1984 to Spherical Mercator
point.transform(epsg4326, map.getProjectionObject());
sitePoints.push(point);
}
sitePoints.push(sitePoints[0]);
var linearRing = new OpenLayers.Geometry.LinearRing(sitePoints);
var geometry = new OpenLayers.Geometry.Polygon([linearRing]);
var polygonFeature = new OpenLayers.Feature.Vector(geometry, null, siteStyle);
vectors.addFeatures([polygonFeature]);
答案 1 :(得分:3)
对于OpenLayers 6,它略有不同,并且花了一些时间才弄清楚。因此,我在此处粘贴了OL6的相关代码。
coordinates
的类型为[[[number]]](这是多边形的GeoJson标准)。
styles
不在范围内(如果有人感兴趣,我可以将其粘贴在这里,但是每个应用程序都可以对其进行不同的定义)。
var VectorSource = ol.source.Vector;
var {Tile, Vector} = ol.layer; //import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer.js';
var TileLayer = Tile;
var VectorLayer = Vector;
var map = new ol.Map(...);
function drawPolygonOnMap(coordinates) {
const polygonFeature = new ol.Feature(
new ol.geom.Polygon(coordinates).transform('EPSG:4326','EPSG:3857'));
let source = new VectorSource({
features: [polygonFeature]
});
var layer = new VectorLayer({
source: source,
style: styles
});
map.addLayer(layer);
}