在OpenLayers地图中显示多边形

时间:2019-06-05 18:29:05

标签: javascript openlayers-3

我要绘制的点(经度,纬度)为多边形:

      var maxPoint = [36.283, -114.368];
      var geoSquare = [ minPoint, [minPoint[0], maxPoint[1]], maxPoint, [maxPoint[0], minPoint[1]]];
      var polygonFeature = new Feature(
              new Polygon(geoSquare));

我正在通过以下方式绘制地图:

      var map = new Map({
        interactions: defaultInteractions().extend([new Drag()]),
        layers: [
          new TileLayer({
            source: new TileJSON({
              url: 'https://maps.siemens.com/styles/osm-bright.json'
            })
          }),
          new VectorLayer({
            source: new VectorSource({
              features: [polygonFeature]
            }),
            style: new Style({
              stroke: new Stroke({
                width: 3,
                color: [255, 0, 0, 1]
              }),
              fill: new Fill({
                color: [0, 0, 255, 0.6]
              })
            })
          })
        ],
        target: 'map',
        view: new View({
          center: [0, 0],
          zoom: 2
        })
      });

此多边形位于南加州附近,但我完全看不到地图上的正方形。怎么了?

编辑

这里是jsfiddle

1 个答案:

答案 0 :(得分:1)

功能坐标必须为LonLat格式,并且必须转换为视图投影。多边形环必须在同一点开始和结束,并且多边形需要额外一对[],因为它们可以具有附加的内部环(孔)。或者,您可以根据范围创建多边形。这些都可以。

  var minPoint = [-121.091, 32.92];
  var maxPoint = [-114.368, 36.283];
  var geoSquare = [[minPoint, [minPoint[0], maxPoint[1]], maxPoint, [maxPoint[0], minPoint[1]], minPoint]];
  var polygonFeature = new Feature(
    new Polygon(geoSquare).transform('EPSG:4326','EPSG:3857'));



  var minPoint = [-121.091, 32.92];
  var maxPoint = [-114.368, 36.283];
  var polygonFeature = new Feature(
    Polygon.fromExtent(minPoint.concat(maxPoint)).transform('EPSG:4326','EPSG:3857'));


  var minPoint = fromLonLat([-121.091, 32.92]);
  var maxPoint = fromLonLat([-114.368, 36.283]);
  var geoSquare = [[minPoint, [minPoint[0], maxPoint[1]], maxPoint, [maxPoint[0], minPoint[1]], minPoint]];
  var polygonFeature = new Feature(
    new Polygon(geoSquare));


  var minPoint = fromLonLat([-121.091, 32.92]);
  var maxPoint = fromLonLat([-114.368, 36.283]);
  var polygonFeature = new Feature(
    Polygon.fromExtent(minPoint.concat(maxPoint)));