天天看點

openlayers結合turf.js 做空間分析

turf.js是一個空間分析的gis庫,封裝了很多常用的空間分析算法,比如相交,緩沖,點在面内等等;在做gis開發的時候,gis渲染引擎結合該庫非常友善,不需要自己動手做空間分析的相關計算;本文用openlayers結合turf.js做個簡單的相交分析

1 具體思路

 使用openlayers建立兩個多邊形,然後利用turf.js的turf.intersect方法做空間相交分析,得到兩個多邊形相交的幾何部分,然後用openlayers繪制高亮凸顯出來。

2 效果和代碼如下

openlayers結合turf.js 做空間分析
import * as ol from 'ol';
import * as layer from 'ol/layer';
import * as source from 'ol/source';
import * as style from 'ol/style';
import * as geom from 'ol/geom';
import 'ol/ol.css';
import turf from "turf";
var map = new ol.Map({
  layers:[
    new layer.Tile({
        source:new source.OSM()
    })
  ],
  target: "map",
  view: new ol.View({
    center: [122.520217, 45.535693],
    zoom: 9,
    projection: "EPSG:4326"
  })
});
// 建立source對象
var VectorSource = new source.Vector({
  features: []            // 值是一個feature數組   source:features  1:N
});
// 建立layer對象
var VectorLayer = new layer.Vector({
  source: VectorSource    // layer-source  1:1
});
//将layer添加到map
map.addLayer(VectorLayer);
var pt1 = [
  [
    [122.801742, 45.48565],
    [122.801742, 45.60491],
    [122.584762, 45.60491],
    [122.584762, 45.48565],
    [122.801742, 45.48565]
  ]
];
var pt2 = [
  [
    [122.520217, 45.535693],
    [122.64038, 45.553967],
    [122.720031, 45.526554],
    [122.669906, 45.507309],
    [122.723464, 45.446643],
    [122.532577, 45.408574],
    [122.487258, 45.477466],
    [122.520217, 45.535693]
  ]
];

var poly1 = turf.polygon(
  [
    pt1[0]
  ],
  {
    name: "大頭1",
    age: "280"
  }
);
var poly2 = turf.polygon(
  [
    pt2[0]
  ],
  {
    name: "大頭",
    age: "28"
  }
);
/**
 * 建立兩個多邊形到地圖
 */
function createPolygon(ptArr) {
  var feature = new ol.Feature({
    geometry: new geom.Polygon(ptArr)
  });
  VectorSource.addFeature(feature);
}
createPolygon(pt1);
createPolygon(pt2);

// 擷取相交幾何坐标
var intersection = turf.intersect(poly1, poly2);
var geometry1 = intersection.geometry.coordinates;
// 建立相交圖層
var IntersectLayer = new layer.Vector({
  source: new source.Vector({
    features: [
      new ol.Feature({
        geometry: new geom.Polygon(geometry1)
      })
    ] 
  })
});
// 定義相交樣式
var IntersectStyle= new style.Style({
  stroke: new style.Stroke({
    color: "blue",
    width: 3
  }),
  fill: new style.Fill({
    color: "rgba(202, 12, 22, 0.5)"
  })
});
IntersectLayer.setStyle(IntersectStyle);
// 添加相交圖層到地圖
map.addLayer(IntersectLayer);
           

繼續閱讀