繪製扇形

範例展示

原始碼

copy
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>繪製扇形 - Map8 Platform Documentation</title>
    <link rel="stylesheet" href="https://api.map8.zone/css/gomp.css?key=[YOUR_KEY_HERE]" />
    <style>
        #map{
            height: 400px; 
            width: 100%;
        }
    </style>
</head>
<body>
    <div id="map"></div>
    <input type="radio" name="radius" value="0.2"> 200公尺
    <input type="radio" name="radius" value="0.15"> 150公尺
    <input type="radio" name="radius" value="0.1" checked> 50公尺
    
    <script type="text/javascript" src="https://api.map8.zone/maps/js/gomp.js?key=[YOUR_KEY_HERE]"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/Turf.js/5.1.5/turf.min.js"></script>
    <script type="text/javascript">
        gomp.accessToken = '[YOUR_KEY_HERE]';
        var map = new gomp.Map({
            container: 'map', // 地圖容器 ID
            style: 'https://api.map8.zone/styles/go-life-maps-tw-style-std/style.json', // 地圖樣式檔案位置
            maxBounds: [[105, 15], [138.45858, 33.4]], // 台灣地圖區域
            center: [121.54885, 25.037853], // 初始中心座標,格式為 [lng, lat]
            zoom: 16, // 初始 ZOOM LEVEL; [0-20, 0 為最小 (遠), 20 ;最大 (近)]
            minZoom: 6, // 限制地圖可縮放之最小等級, 可省略, [0-19.99]
            maxZoom: 19.99, // 限制地圖可縮放之最大等級, 可省略 [0-19.99]
            speedLoad: false,
            attributionControl: false
        }).addControl(new gomp.AttributionControl({
            compact: false
        }));
      map.on('load', () => {
        initLayer(0.1);
      });
      function initLayer(radius) {
        if (map.getLayer('maine') != undefined){
          map.removeLayer('maine');
          map.removeSource('maine');
        }
        let center = turf.point([121.54885, 25.037853]);
        let bearing1 = -90; // 起始角度
        let bearing2 = 0.1; // 結束角度
        let data = turf.sector(center, radius, bearing1, bearing2);
        map.addSource('maine', {
          type: 'geojson',
          data: data,
        });
        map.addLayer({
          id: 'maine',
          type: 'fill',
          source: 'maine',
          layout: {},
          paint: {
            'fill-color': 'red',
            'fill-opacity': 0.5,
          },
        });
      }
      // 監聽半徑選擇的 radio
      let radios = document.querySelectorAll('input[name="radius"]');
      radios.forEach(function (radio) {
        radio.addEventListener('change', function () {
          if (this.checked) {
            let selectedRadius = parseFloat(this.value);
            initLayer(selectedRadius);
          }
        });
      });


    </script>
</body>
</html>