0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Turf.jsAdvent Calendar 2020

Day 10

図形を単純化する simplify

Last updated at Posted at 2020-12-09

複雑な図形を間引いてシンプルな図形にします。
Ramer-Douglas-Peucker というアルゴリズムを使っているそうです。

cap.gif

const polygon1 = {"type":"Feature","properties":{"pref":22,"name":"静岡県"},"geometry":{"type":"Polygon","coordinates":[省略]}};

const polygon2 = {"type":"Feature","properties":{"pref":23,"name":"愛知県"},"geometry":{"type":"Polygon","coordinates":[省略]}};

const map = new mapboxgl.Map({
  container: 'map',
  bounds: turf.bbox(turf.featureCollection([polygon1, polygon2])),
  fitBoundsOptions: { padding: { bottom: 50, top: 50, right: 50, left: 50 } },
  style: {
    version: 8,
    sources: {
      OSM: {
        type: "raster",
        tiles: [ "https://a.tile.openstreetmap.org/{z}/{x}/{y}.png" ],
        tileSize: 256,
        attribution: "OpenStreetMap",
      },
      polygons: {
        'type': 'geojson',
        'data': {
          "type": "FeatureCollection",
          "features": [ polygon1, polygon2 ]
        }
      }      
    },
    layers: [
      {
        id: "BASEMAP",
        type: "raster",
        source: "OSM",
      },
      {
        'id': 'polygons',
        'type': 'fill',
        'source': 'polygons',
        'paint': {
          'fill-outline-color': '#000000',
          'fill-color': '#FF0000',
          'fill-opacity': 0.7
        }
      },
    ],
  },      
});

document.getElementById('simplify').addEventListener('click', () => {
  const tole = Number(document.getElementById('tole').value);

  turf.simplify(polygon1, { tolerance: tole, highQuality: false, mutate: true });
  turf.simplify(polygon2, { tolerance: tole, highQuality: false, mutate: true });

  const dataSource = map.getSource('polygons');
  dataSource.setData({
    "type": "FeatureCollection",
    "features": [
      polygon1, polygon2
    ]    
  });
});

使い方は、turf.simplify(図形, { tolerance: 間引く距離, highQuality: 高/低精度 }) です。
Ramer-Douglas-Peucker algorithm は、tolerance で指定した距離にある点を間引くようなので、同じ tolerance で simplify を繰り返し実行しても、初回しかシンプル化されません。
highQuality:true/false の違いは、あまり体感できませんでした。

また、サンプルで隣り合うポリゴン2つをそれぞれシンプル化していますが、結果を見て分かるとおり、接合面は一致しません。
単一の図形を間引きたいときに使うとよさそうです。

完全なコード

参考

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?