Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What are the problem?

posted at

updated at

図形を単純化する simplify

複雑な図形を間引いてシンプルな図形にします。
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つをそれぞれシンプル化していますが、結果を見て分かるとおり、接合面は一致しません。
単一の図形を間引きたいときに使うとよさそうです。

完全なコード

参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
1
Help us understand the problem. What are the problem?