简体   繁体   English

向 OpenLayers 6 添加功能

[英]add feature to OpenLayers 6

I am trying to add geometry, LineString to the VectorLayers using OpenLayers 6, but failed.我正在尝试使用 OpenLayers 6 将几何体 LineString 添加到 VectorLayers,但失败了。 Appreciate your help.感谢你的帮助。

Here is my code这是我的代码

var coordinates = [
  [new ol.geom.Point(103.8797182, 1.3160559)],
  [new ol.geom.Point(103.8800485, 1.3161336)],
  [new ol.geom.Point(103.8800889, 1.3161672)],
  [new ol.geom.Point(103.8801166, 1.3162658)],
  [new ol.geom.Point(103.8798829, 1.3171543)],
];
console.log(coordinates);

layer = new ol.layer.Vector({
  source: new ol.source.Vector({
    features: [
      new ol.Feature({
        geometry: new ol.geom.LineString(coordinates),
        name: "Line",
      }),
    ],
  }),
  style: function (feature) {
    console.log(feature.getGeometry().getType());
    return styles[feature.getGeometry().getType()];
  },
});

powerMap.addLayer(layer);

Is there anything wrong with the code as the layer didn't display.由于图层未显示,代码有什么问题吗?

EDIT: I have implemented Mark's suggestion and here is the solution:编辑:我已经实施了马克的建议,这是解决方案:

var coordinates = [
    [ 103.7960334725309, 1.4494121393815099 ],
    [ 103.79617186914557, 1.4491070600247167 ],
    [ 103.79642909728881, 1.4489874603770377 ],
    [ 103.79664709373664, 1.4489591347536637 ],
    [ 103.79904789809408, 1.4501025693183976 ],
    [ 103.79917449669307, 1.449834325824822 ]
];

var lines = new ol.geom.LineString(coordinates).transform('EPSG:4326', powerMap.getView().getProjection());

var layer = new ol.layer.Vector({
  source: new ol.source.Vector({
    features: [
      new ol.Feature({
        geometry: lines,
        name: "Line",
      }),
    ],
  }),
  style: function (feature) {
    console.log(feature.getGeometry().getType());
    return styles[feature.getGeometry().getType()];
  },
});

powerMap.addLayer(layer);

Coordinates should be an array of coordinates, not an array of Point geometries坐标应该是坐标数组,而不是点几何数组

var coordinates = [
  [103.8797182, 1.3160559],
  [103.8800485, 1.3161336],
  [103.8800889, 1.3161672],
  [103.8801166, 1.3162658],
  [103.8798829, 1.3171543],
];

You will probably also need to transform the LineString to the map projection您可能还需要将 LineString 转换为 map 投影

new ol.geom.LineString(coordinates).transform('EPSG:4326', map.getView().getProjection())

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

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