javascript - 风格矩形的最小尺寸

标签 javascript openlayers-3

我正在编写一个应用程序,用户可以在其中标记世界地图上的区域。现在这些区域可以非常小,因此在不放大时很难点击它们。

有没有一种方法可以定义(例如在样式函数中)(矩形)特征应该始终至少以例如10px × 10px?

更新:我目前使用的一些代码:

在绘图方面:

var draw = new ol.interaction.Draw({
  source: vectorSource,
  type: 'LineString',
  geometryFunction: function(coordinates, geometry) {
    if(!geometry) {
      geometry = new ol.geom.Polygon(null);
    }
    var start = coordinates[0];
    var end = coordinates[1];
    geometry.setCoordinates([[
      start,
      [start[0], end[1]],
      end,
      [end[0], start[1]],
      start
    ]]);
    return geometry;
  },
  maxPoints: 2
});

draw.on('drawend', function(e) {
  var extent = e.feature.getGeometry().getExtent();
  extent = app.map.rlonlate(extent); // own function to convert it from map coordinates into lat/lon
  // some code to save the extent to the database
});

在显示方面:

vectorSource.addFeature(
  new ol.Feature({
    geometry: ol.geom.Polygon.fromExtent(app.map.lonlate(extent)),
    // … some more custom properties like a display name …
  })
);

样式函数:

function(feature) {
  return [new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: feature.get('mine') ? '#204a87' : '#729fcf',
      width: 2
    }),
    fill: new ol.style.Fill({
      color: 'rgba(255, 255, 255, ' + (feature.get('mine') ? '0.5' : '0.2') + ')'
    })
  })];
}

最佳答案

使用样式函数是个好主意。样式函数的第二个参数是 resolution,您可以使用它来检查要素几何是否小于例如当前分辨率为 10 像素:

var styleFn = function(feature, resolution) {
  var minSizePx = 30;
  var minSize = minSizePx * resolution;
  var extent = feature.getGeometry().getExtent();

  if (ol.extent.getWidth(extent) < minSize || ol.extent.getHeight(extent) < minSize) {
    // special style for polygons that are too small
    var center = new ol.geom.Point(ol.extent.getCenter(extent));
    return new ol.style.Style({
      geometry: center,
      image:  ...
  } else {
    // normal style
    return defaultStyle;
  }
};

http://jsfiddle.net/ukc0nmy2/1/

关于javascript - 风格矩形的最小尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38960320/

相关文章:

javascript - 如何使用 openlayers3 对 PNG 图像进行动画处理

javascript - js如何返回内层Promise?

javascript - 即使功能被覆盖层隐藏,鼠标光标也会在功能上变化

javascript - 拖动功能后关闭弹出叠加层

javascript - 多个 .html 页面上的持续动画

javascript - 开放层 : how to turn on visibility of a layer?

javascript - 如何从 OpenLayers 中的 MultiLineString 中删除线串?

javascript - 使用 bootstrap 关闭 angular.js 中的所有对话框

javascript - 如何在普通 javascript 中使用类触发特定 html 元素上的事件

javascript - CoffeeScript 编译 : Unexpected IF