[Flutter]独自マップを表示してみる

地球のマップじゃなくてエオルゼアマップを表示してみる。

マップをタイル状にする

GoogleMapなどはそれぞれの倍率で各256pxのタイル状の画像で構成されている。
ので、自前のマップを使う場合も同様に256pxのタイル状マップを作成する必要がある。

手作業でも作れるけど、ツラいのでツールを使う。
とりあえず適当にJavaScriptプロジェクトというかフォルダを作って image-map-tilesライブラリをインストールする。

mkdir image_map_titles
cd image_map_titles
npm i image-map-tiles -S

image-map-tilesを使用して変換するスクリプトを適当に…(ホントテキトウ…

const imageMapTiles = require('image-map-tiles');

var options = {
    'outputDir': 'map_g12/output',
    'zoom': 3,
    'tileHeight': 256,
    'tileWidth': 256
}

imageMapTiles('map_g12/input/map_5_tempest.png', options);

入力する画像は切りよく2048pxしてある。
実行すればタイル状の画像が出力される。

はずなんだけど、image-map-tilesが更新されなさ過ぎてsharpにcropがないって怒られるので、少し修正する。

	function makeThumbnail(){
		return new Promise(function(resolve, reject) {
			//Get new copy of image so it isn't polluted by scale transforms.
			var thumbnail = sharp(imagePath);

			thumbnail
			.resize(250, 250)
			// .crop(sharp.gravity.center)
			.toFile(outputDir + 'thumbnail.jpg', function(err){
				if (err) {
					console.log('Thumbnail Error', err);
				} else {
					console.log('Thumbnail Create');
				}
				resolve();
			})
		});
	}

cropの行をコメントアウト。
サムネイル部分だから別に要らないでしょう…知らんけど。

Flutterで表示

assetsフォルダを作ってその中に画像を入れる。

pubspec.yamlを編集する
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
    - assets/tempest/0/0/
    - assets/tempest/1/0/
    - assets/tempest/1/1/
    - assets/tempest/2/0/
    - assets/tempest/2/1/
    - assets/tempest/2/2/
    - assets/tempest/2/3/
    - assets/tempest/3/0/
    - assets/tempest/3/1/
    - assets/tempest/3/2/
    - assets/tempest/3/3/
    - assets/tempest/3/4/
    - assets/tempest/3/5/
    - assets/tempest/3/6/
    - assets/tempest/3/7/

assetsフォルダ以下全て。
選択して読みたい場合は、ファイル毎に指定する。

ソースを編集する

前回のソースはネット上の地図を表示するようにしてたけど、今回はassets内の画像を使用するように変更する。

import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return FlutterMap(
      options: MapOptions(
        center: LatLng(0, 0),
        zoom: 3.0,
        maxZoom: 3.0,
      ),
      layers: [
        TileLayerOptions(
          tileProvider: const AssetTileProvider(),
          urlTemplate: "assets/tempest/{z}/{x}/{y}.jpg",
          attributionBuilder: (_) {
            return const Text(
                "©2010-2021 SQUARE ENIX CO., LTD. All Rights Reserved.");
          },
        ),
        MarkerLayerOptions(
          markers: [
            Marker(
              width: 20.0,
              height: 20.0,
              point: LatLng(0, 0),
              builder: (ctx) => Container(
                child: FlutterLogo(),
              ),
            ),
          ],
        ),
      ],
    );
  }
}

実行してみる

上下は白背景だったり、左右は繰り返し地図が表示されちゃうけど表示できました。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

three × 5 =