简体   繁体   English

OpenLayers - 如何从现有的 lonLat 点绘制多边形?

[英]OpenLayers - how do I draw a Polygon from existing lonLat points?

I have in my database longitude-latitude verticies from user-defined polygons.我的数据库中有来自用户定义多边形的经纬度顶点。 My questions is: how do I recreate and display them on a map now?我的问题是:我现在如何在地图上重新创建和显示它们? This is quite easy to do with the Google Maps API, but I can't find any documentation or examples on how to do this with OpenLayers.使用 Google Maps API 很容易做到这一点,但我找不到关于如何使用 OpenLayers 做到这一点的任何文档或示例。 Has anyone had any experience doing this?有没有人有这样做的经验?

After a lot of experimenting, I found out how to do it:经过大量的实验,我发现了如何做到这一点:

let sitePoints = [];
let siteStyle = {
  // style_definition
};

let epsg4326 = new OpenLayers.Projection("EPSG:4326");
for (let i in coordinates) {
  let coord = coordinates[i];
  let 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]);

let linearRing = new OpenLayers.Geometry.LinearRing(sitePoints);
let geometry = new OpenLayers.Geometry.Polygon([linearRing]);
let polygonFeature = new OpenLayers.Feature.Vector(geometry, null, siteStyle);
vectors.addFeatures([polygonFeature]);

OpenLayers 6开放层 6

it is slightly different for OpenLayers 6, and it took ma a while to figure it out. OpenLayers 6 略有不同,我花了一段时间才弄明白。 So I paste here the relevant code for OL6.所以我把OL6的相关代码贴在这里。

coordinates are of type [[[number]]] (which is the GeoJson standard for polygon). coordinates类型为 [[[number]]] (这是多边形的 GeoJson 标准)。

styles is out-of-scope (i can paste it here if someone is interested, but every app can define it differently). 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM