0
0

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.

mapboxのraster tileを表示する際、zoom、x、y以外のパラメータがある場合

Last updated at Posted at 2021-03-17

Raster Tile

注:このMapbox提供のサンプルはstyleにベタ書きなのであんまり良くない

普通は標準的な地図タイルにオーバーレイすると思う

const map = new mapboxgl.Map({
  container: "map",
  style: "mapbox://styles/mapbox/streets-v9",
  zoom: 11,
})

map.on("load", () => {
  const sourceId = "sourceId"
  const layerId = "layerId"

  // TileJSON Spec
  // https://github.com/mapbox/tilejson-spec/tree/master/2.2.0
  // tilesは最低1つ必要で、複数あった場合はどれを使われても同じデータを返す必要がある(ロードバランス的な)
  // z x y以外のパラメータの指定はできないっぽい
  map.addSource(sourceId, {
    type: "raster",
    tiles: ["https://localhost:3000/{z}/{x}/{y}.png"],
    tileSize: 256,
  })

  map.addLayer({
    id: layerId,
    type: "raster",
    source: sourceId,
    layout: {
      visibility: "visible",
    },
  })

  map.setPaintProperty(layerId, "raster-opacity", 0.5)
})

問題

tiles: ["https://localhost:3000/{z}/{x}/{y}.png"]

ここがzoom level、 x、 yしか渡せず、仮に日付毎とかのデータを表示したかったら如何ともし難い。

解決方法その1

LayerとSourceを削除して、新たに別のtilesをSourceとするLayerを追加する。ユーザー個別の情報を元にするとか、事前にパラメーターの予測ができないような状況ではこれ以外やりようがないかも。

const sourceId = "sourceId"
const layerId = "layerId"

// Layerも消さないとSourceを掴んだままになるので、Sourceが消えない
map.removeLayer(layerId)
map.removeSource(sourceId)
map.addSource(sourceId, {
  type: "raster",
  tiles: ["あらたなURL"],
  tileSize: 256,
})

map.addLayer({
  id: layerId,
  type: "raster",
  source: sourceId,
  layout: {
    visibility: "visible",
  },
})
map.setPaintProperty(layerId, "raster-opacity", 0.5)

解決方法2

事前にSourceとLayerのペアをあるだけ追加しておく。その上で、使用するIDにはindexを付けておくとかする。さらにLayerはvisibility: noneにしておく。

必要に応じて必要なLayerだけを切り替えるように表示・非表示してやる。

const index = 1
const layerId = `layerId-${index}`
const visibility = map.getLayoutProperty(layerId, "visibility")
map.setLayoutProperty(
  layerId,
  "visibility",
  visibility == "visible" ? "none" : "visible"
)

Source(表示したLayerが引っ張ってくるSource)のロード検知

map.on("sourcedata", (event) => {
  console.log("event.isSourceLoaded:", event.isSourceLoaded)
  console.log("event.sourceId:", event.sourceId)
})
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?