Openlayers6 Examples学习笔记(3)

文章目录

  • EPSG:4326
  • Geographic Editing(地理要素编辑)
  • Custom Interactions
  • Earthquake Clusters

EPSG:4326

  1. 创建单位为度的比例尺
  2. 将视图的坐标系统设置为EPSG:4326(默认是EPSG:3857——Web 墨卡托投影)
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import {defaults as defaultControls, ScaleLine} from 'ol/control';
import TileLayer from 'ol/layer/Tile';
import TileWMS from 'ol/source/TileWMS';


var layers = [
  new TileLayer({
    source: new TileWMS({
      url: 'https://ahocevar.com/geoserver/wms',
      params: {
        'LAYERS': 'ne:NE1_HR_LC_SR_W_DR',
        'TILED': true
      }
    })
  })
];

var map = new Map({
  controls: defaultControls().extend([
    new ScaleLine({
      units: 'degrees'
    })
  ]),
  layers: layers,
  target: 'map',
  view: new View({
    projection: 'EPSG:4326',
    center: [0, 0],
    zoom: 2
  })
});

Geographic Editing(地理要素编辑)

Openlayers6 Examples学习笔记(3)_第1张图片

  1. useGeographic在’ol/proj’模块中调用该函数可以使地图视图使用地理坐标(即使视图投影不是地理坐标)。
  2. 4个交互:select、modify、draw、snap
  3. 绘制要素时使用到的交互:draw、snap
  4. 修改要素时使用到的交互:select、modify、snap
import 'ol/ol.css';
import {Map, View} from 'ol/index';
import GeoJSON from 'ol/format/GeoJSON';
import {Modify, Select, Draw, Snap} from 'ol/interaction';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
import {OSM, Vector as VectorSource} from 'ol/source';
import {useGeographic} from 'ol/proj';

// 使用地图坐标
useGeographic();

var source = new VectorSource({
  url: require('./data/geojson/countries.geojson'),
  format: new GeoJSON()
});

var map = new Map({
  target: 'map',
  layers: [
    new TileLayer({
      source: new OSM()
    }),
    new VectorLayer({
      source: source
    })
  ],
  view: new View({
    center: [0, 0],
    zoom: 2
  })
});

var select = new Select();

var modify = new Modify({
  features: select.getFeatures()
});

var draw = new Draw({
  type: 'Polygon',
  source: source
});

var snap = new Snap({
  source: source
});

function removeInteractions() {
  map.removeInteraction(modify);
  map.removeInteraction(select);
  map.removeInteraction(draw);
  map.removeInteraction(select);
}

var mode = document.getElementById('mode');
function onChange() {
  removeInteractions();
  switch (mode.value) {
    case 'draw': {
      map.addInteraction(draw);
      map.addInteraction(snap);
      break;
    }
    case 'modify': {
      map.addInteraction(select);
      map.addInteraction(modify);
      map.addInteraction(snap);
      break;
    }
    default: {
      // pass
    }
  }
}
mode.addEventListener('change', onChange);
onChange();

Custom Interactions

  1. 自定义交互,在call方法中声明交互涉及到的鼠标事件。
import 'ol/ol.css';
import Feature from 'ol/Feature';
import Map from 'ol/Map';
import View from 'ol/View';
import {
  LineString,
  Point,
  Polygon
} from 'ol/geom';
import {
  defaults as defaultInteractions,
  Pointer as PointerInteraction
} from 'ol/interaction';
import {
  Tile as TileLayer,
  Vector as VectorLayer
} from 'ol/layer';
import {
  TileJSON,
  Vector as VectorSource
} from 'ol/source';
import {
  Fill,
  Icon,
  Stroke,
  Style
} from 'ol/style';

// 自定义交互
var Drag = /*@__PURE__*/ (function (PointerInteraction) {
  function Drag() {
    PointerInteraction.call(this, {
      handleDownEvent: handleDownEvent,
      handleDragEvent: handleDragEvent,
      handleMoveEvent: handleMoveEvent,
      handleUpEvent: handleUpEvent
    });

    /**
     * @type {import("../src/ol/coordinate.js").Coordinate}
     * @private
     */
    this.coordinate_ = null;

    /**
     * @type {string|undefined}
     * @private
     */
    this.cursor_ = 'pointer';

    /**
     * @type {Feature}
     * @private
     */
    this.feature_ = null;

    /**
     * @type {string|undefined}
     * @private
     */
    this.previousCursor_ = undefined;
  }

  if (PointerInteraction) Drag.__proto__ = PointerInteraction;
  Drag.prototype = Object.create(PointerInteraction && PointerInteraction.prototype);
  Drag.prototype.constructor = Drag;

  return Drag;
}(PointerInteraction));


/**
 * @param {import("../src/ol/MapBrowserEvent.js").default} evt Map browser event.
 * @return {boolean} `true` to start the drag sequence.
 */
function handleDownEvent(evt) {
  var map = evt.map;

  var feature = map.forEachFeatureAtPixel(evt.pixel,
    function (feature) {
      return feature;
    });

  if (feature) {
    // 记录当前鼠标按下的坐标
    this.coordinate_ = evt.coordinate;
    this.feature_ = feature;
  }

  return !!feature;
}


/**
 * @param {import("../src/ol/MapBrowserEvent.js").default} evt Map browser event.
 */
function handleDragEvent(evt) {
  // evt.coordinate为当前鼠标所在位置的坐标
  // this.coordinate_为鼠标按下时的坐标
  var deltaX = evt.coordinate[0] - this.coordinate_[0];
  var deltaY = evt.coordinate[1] - this.coordinate_[1];

  var geometry = this.feature_.getGeometry();
  // 平移几何要素
  geometry.translate(deltaX, deltaY);
  // 记录拖拽后的坐标
  this.coordinate_[0] = evt.coordinate[0];
  this.coordinate_[1] = evt.coordinate[1];
}


/**
 * @param {import("../src/ol/MapBrowserEvent.js").default} evt Event.
 */
function handleMoveEvent(evt) {
  // 判断当前是否处于移动样式
  if (this.cursor_) {
    var map = evt.map;
    var feature = map.forEachFeatureAtPixel(evt.pixel,
      function (feature) {
        return feature;
      });
    // 获取呈现此地图的DOM元素
    var element = evt.map.getTargetElement();
    if (feature) {
      if (element.style.cursor != this.cursor_) {
        // 记录先前鼠标的样式
        this.previousCursor_ = element.style.cursor;
        element.style.cursor = this.cursor_;
      }
    } else if (this.previousCursor_ !== undefined) {
      // 将当前ele变回先前的样式
      element.style.cursor = this.previousCursor_;
      this.previousCursor_ = undefined;
    }
  }
}


/**
 * @return {boolean} `false` to stop the drag sequence.
 */
function handleUpEvent() {
  this.coordinate_ = null;
  this.feature_ = null;
  return false;
}

// 点要素
var pointFeature = new Feature(new Point([0, 0]));
// 线要素
var lineFeature = new Feature(
  new LineString([
    [-1e7, 1e6],
    [-1e6, 3e6]
  ]));
// 面要素
var polygonFeature = new Feature(
  new Polygon([
    [
      [-3e6, -1e6],
      [-3e6, 1e6],
      [-1e6, 1e6],
      [-1e6, -1e6],
      [-3e6, -1e6]
    ]
  ]));

var key = '您的mapbox的key';

var map = new Map({
  interactions: defaultInteractions().extend([new Drag()]),
  layers: [
    new TileLayer({
      source: new TileJSON({
        url: 'https://a.tiles.mapbox.com/v4/aj.1x1-degrees.json?access_token=' + key
      })
    }),
    new VectorLayer({
      source: new VectorSource({
        features: [pointFeature, lineFeature, polygonFeature]
      }),
      style: new Style({
        image: new Icon({
          anchor: [0.5, 46],
          anchorXUnits: 'fraction',
          anchorYUnits: 'pixels',
          opacity: 0.95,
          src: require('./data/icon.png')
        }),
        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
  })
});

Earthquake Clusters

  1. 创建初始的样式——五角星
  2. 根据分辨率设定聚合要素样式的半径
  3. 设置聚合要素与一般要素的样式
  4. 选中聚合要素时的样式
  5. 设置选中交互时的条件
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import {
  createEmpty,
  getWidth,
  getHeight,
  extend
} from 'ol/extent';
import KML from 'ol/format/KML';
import {
  defaults as defaultInteractions,
  Select
} from 'ol/interaction';
import {
  Tile as TileLayer,
  Vector as VectorLayer
} from 'ol/layer';
import {
  Cluster,
  Stamen,
  Vector as VectorSource
} from 'ol/source';
import {
  Circle as CircleStyle,
  Fill,
  RegularShape,
  Stroke,
  Style,
  Text
} from 'ol/style';


var earthquakeFill = new Fill({
  color: 'rgba(255, 153, 0, 0.8)'
});
var earthquakeStroke = new Stroke({
  color: 'rgba(255, 204, 0, 0.2)',
  width: 1
});
var textFill = new Fill({
  color: '#fff'
});
var textStroke = new Stroke({
  color: 'rgba(0, 0, 0, 0.6)',
  width: 3
});
var invisibleFill = new Fill({
  color: 'rgba(255, 255, 255, 0.01)'
});

// 创建初始的样式——五角星
function createEarthquakeStyle(feature) {
  // 2012_Earthquakes_Mag5.kml stores the magnitude of each earthquake in a
  // standards-violating  tag in each Placemark.  We extract it
  // from the Placemark's name instead.
  var name = feature.get('name');
  var magnitude = parseFloat(name.substr(2));
  var radius = 5 + 20 * (magnitude - 5);

  return new Style({
    geometry: feature.getGeometry(),
    image: new RegularShape({
      radius1: radius,
      radius2: 3,
      points: 5,
      angle: Math.PI,
      fill: earthquakeFill,
      stroke: earthquakeStroke
    })
  });
}

var maxFeatureCount;
var vector = null;
// 根据分辨率设定聚合要素样式的半径
var calculateClusterInfo = function (resolution) {
  maxFeatureCount = 0;
  var features = vector.getSource().getFeatures();
  var feature, radius;
  // 遍历聚合要素
  for (var i = features.length - 1; i >= 0; --i) {
    feature = features[i];
    var originalFeatures = feature.get('features');
    // 创建一个空的范围
    var extent = createEmpty();
    var j = (void 0),
      jj = (void 0);
    for (j = 0, jj = originalFeatures.length; j < jj; ++j) {
      // 修改范围以包括另一个范围。(前者包含后者)
      extend(extent, originalFeatures[j].getGeometry().getExtent());
    }
    maxFeatureCount = Math.max(maxFeatureCount, jj);
    radius = 0.25 * (getWidth(extent) + getHeight(extent)) /
      resolution;
    // 设置半径
    feature.set('radius', radius);
  }
  console.log(maxFeatureCount);
  
};

var currentResolution;

function styleFunction(feature, resolution) {
  if (resolution != currentResolution) {
    calculateClusterInfo(resolution);
    currentResolution = resolution;
  }
  var style;
  // 设置数字的大小为聚合feature的数量
  var size = feature.get('features').length;
  if (size > 1) {
    // 显示聚合
    style = new Style({
      image: new CircleStyle({
        radius: feature.get('radius'),
        fill: new Fill({
          color: [255, 153, 0, Math.min(0.8, 0.4 + (size / maxFeatureCount))]
        })
      }),
      text: new Text({
        text: size.toString(),
        fill: textFill,
        stroke: textStroke
      })
    });
  } else {
    // 显示单个样式
    var originalFeature = feature.get('features')[0];
    style = createEarthquakeStyle(originalFeature);
  }
  return style;
}

// 选中聚合要素时的样式
function selectStyleFunction(feature) {
  var styles = [new Style({
    image: new CircleStyle({
      radius: feature.get('radius'),
      fill: invisibleFill
    })
  })];
  var originalFeatures = feature.get('features');
  var originalFeature;
  // 恢复聚合前的样式
  for (var i = originalFeatures.length - 1; i >= 0; --i) {
    originalFeature = originalFeatures[i];
    styles.push(createEarthquakeStyle(originalFeature));
  }
  return styles;
}

vector = new VectorLayer({
  source: new Cluster({
    distance: 40,
    source: new VectorSource({
      url: require('./data/kml/2012_Earthquakes_Mag5.kml'),
      format: new KML({
        extractStyles: false
      })
    })
  }),
  style: styleFunction
});

var raster = new TileLayer({
  source: new Stamen({
    layer: 'toner'
  })
});

var map = new Map({
  layers: [raster, vector],
  // 设定选中时的交互,移动或单击
  interactions: defaultInteractions().extend([new Select({
    condition: function (evt) {
      return evt.type == 'pointermove' ||
        evt.type == 'singleclick';
    },
    style: selectStyleFunction
  })]),
  target: 'map',
  view: new View({
    center: [0, 0],
    zoom: 2
  })
});

你可能感兴趣的:(WebGIS)