Mapbox-GL 地図を描画すると右半分にしか表示されない
こんな状態になる。言葉では説明しづらいが、ホイールでズームイン/アウトしたときの中心座標も右にズレてる。
App.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
< template >
< div id = "app" >
< div id = "map" ></ div >
</ div >
</ template >
< script >
import mapboxgl from 'mapbox-gl'
mapboxgl.accessToken = '(secret)'
export default {
name: 'App',
mounted() {
// ごく一般的なMapBoxGLによる地図描画
this.map = new mapboxgl.Map({
container: "map",
center: [139.767, 35.681],
zoom: 11
})
this.map.addControl(new mapboxgl.NavigationControl())
},
}
</ script >
< style >
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
#map {
width: 100%;
height: 500px;
}
</ style >
|
原因
単純な話で、text-align: center
と position: absolute
を一緒に使っちゃダメというだけのこと。
MapBox-GLによってDOMに追加されるcanvas要素には、以下の3つのスタイルが直接指定される。
<canvas class="mapboxgl-canvas" width="1247" height="500" style="position: absolute; width: 1247px; height: 500px;"></canvas>
position: absolute
width: (親要素のwidth)
height: (親要素のheight)
ここで、Vue.js では、initで作成されるサンプルのルート要素に以下が指定されている。
<style>
#app {
/* ..略.. */
text-align: center;
}
</style>
特に何も考えずこれを流用していると、
position:absolute
要素のアンカーは左上にあるので、text-aling:center
によって要素の左上が画面の中央に持ってこられてしまった。
解決策
ルート要素の text-align
を消すか、canvasの親要素に text-align: left
などを適用して上書きすればいい。