LoginSignup
4
6

More than 3 years have passed since last update.

Mapbox GL JS で地図上に Hello World を表示する

Last updated at Posted at 2019-08-23

Mapbox とは

  • モバイルや Web アプリケーションのための位置情報データプラットフォーム
  • 位置情報系のモジュール (地図、検索、ナビゲーション) を提供する

About | Mapbox

Mapbox is the location data platform for mobile and web applications. We provide building blocks to add location features like maps, search, and navigation into any experience you create.

Mapbox GL JS とは

  • ベクトル形式の地図タイルデータと Mapbox のスタイルデータを読み込んで WebGL で地図を描画する JavaScript のライブラリ

Mapbox GL JS | Mapbox

Mapbox GL JS is a JavaScript library that uses WebGL to render interactive maps from vector tiles and Mapbox styles.

Mapbox アカウントを作成

Mapbox のアカウントが無い場合は、 Sign up | Mapbox にて作成する必要がある。

アクセストークンを取得

Mapbox GL JS を使うには Mapbox の access token が必要。
Mapbox アカウントを作成すると自動でひとつ作られる (Default public token) のでそれを使えばいい。
Mapbox アクセストークンのページ Account | Mapbox にて access token の値を確認することができる。

サンプルコード

<!DOCTYPE html>
<html>
<head>
  <meta charset='utf-8' />
  <title>Display a map</title>
  <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
  <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.2.1/mapbox-gl.js'></script>
  <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.2.1/mapbox-gl.css' rel='stylesheet' />
  <style>
    body { margin:0; padding:0; }
    #map { position:absolute; top:0; bottom:0; width:100%; }
  </style>
</head>
<body>

<div id='map'></div>

<script>
// 自分のアクセストークンをセット
mapboxgl.accessToken = 'YOUR_MAPBOX_ACCESS_TOKEN';

// 名古屋駅周辺の地図を表示する
var map = new mapboxgl.Map({
  container: 'map', // container id
  style: 'mapbox://styles/mapbox/streets-v11', // stylesheet location
  center: [136.882763, 35.1707925], // starting position [lng, lat]
  zoom: 14 // starting zoom
});

// 名古屋駅の場所にピンを立てる
var marker = new mapboxgl.Marker()
  .setLngLat(map.getCenter())
  .addTo(map);

// Hello World ダイアログボックスを表示する
var markerHeight = 50, markerRadius = 10, linearOffset = 25;
var popupOffsets = {
 'top': [0, 0],
 'top-left': [0,0],
 'top-right': [0,0],
 'bottom': [0, -markerHeight],
 'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1],
 'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1],
 'left': [markerRadius, (markerHeight - markerRadius) * -1],
 'right': [-markerRadius, (markerHeight - markerRadius) * -1]
};
var popup = new mapboxgl.Popup({offset: popupOffsets, className: 'my-class'})
  .setLngLat(map.getCenter())
  .setHTML("<h1>Hello World!</h1>")
  .setMaxWidth("300px")
  .addTo(map);
</script>

</body>
</html>

表示結果

mapbox.png

参考資料

4
6
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
4
6