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
0
Help us understand the problem. What are the problem?

posted at

updated at

図形を回転する transformRotate

角度と基点を指定して図形を回転させます。

cap.gif

let polygon1 = {
  "type": "Feature",
  "properties": {},
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [ 137.796, 34.940 ],
        [ 137.748, 34.882 ],
        [ 137.887, 34.888 ],
        [ 137.796, 34.940 ]
      ]
    ]
  }
};

const dataSource = {
  'type': 'geojson',
  'data': {
    "type": "FeatureCollection",
    "features": [
      polygon1,
    ]    
  }
};

const bounds = turf.bbox(dataSource.data);

let anchor;

const map = new mapboxgl.Map({
  container: 'map',
  bounds: bounds,
  style: {
    version: 8,
    sources: {
      OSM: {
        type: "raster",
        tiles: [
          "https://a.tile.openstreetmap.org/{z}/{x}/{y}.png",
        ],
        tileSize: 256,
        attribution:
        "OpenStreetMap",
      },
    },
    layers: [{
      id: "BASEMAP",
      type: "raster",
      source: "OSM",
      minzoom: 0,
      maxzoom: 18,
    }],
  },      
});

map.once('load', () => {

  map.fitBounds(bounds, { padding: { bottom: 200, top: 200, right: 200, left: 200 }});

  map.addSource('polygons', dataSource);

  map.addLayer({
    'id': 'polygons',
    'type': 'fill',
    'source': 'polygons',
    'paint': {
      'fill-color': '#FF0000',
      'fill-opacity': 0.7
    }
  });

  const center = turf.center(polygon1);
  anchor = new mapboxgl.Marker()
    .setLngLat(center.geometry.coordinates)
    .setDraggable(true)
    .addTo(map);

});

document.getElementById('rotate').addEventListener('click', () => {
  const angle = Number(document.getElementById('dir').value);

  turf.transformRotate(polygon1, angle, { pivot: anchor.getLngLat().toArray(), mutate: true });

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

使い方は、turf.transformRotate(図形, 角度, { pivot: 基点 }); です。
options に mutate: true を付けると、引数に渡した図形の座標群を入れ替えます。
mutate: false (既定値) の場合は返値に移動した図形を返します。

参考

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
0
Help us understand the problem. What are the problem?