본문 바로가기

Flutter/12 Clone 'Used Goods app'

[Flutter] Clone - 당근마켓44(Map - 1)

이번에는 Near 화면에 구글 지도 로딩 및 drag 기능을 추가해보겠습니다.

개발환경 : 윈도우11, 안드로이드 스튜디오, flutter 3.0.1

 

 

 

구현 화면은 아래와 같습니다.

 

 

 

 

 

필요한 패키지는 아래와 같습니다.

 

map: ^1.3.3
latlng: ^0.2.0

 

 

 

./src/screens/near/map_screen.dart 

 

import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:latlng/latlng.dart';
import 'package:map/map.dart';

class MapScreen extends StatefulWidget {
  const MapScreen({Key? key}) : super(key: key);

  @override
  _MapScreenState createState() => _MapScreenState();
}

class _MapScreenState extends State<MapScreen> {
  final _mapController = MapController(
    location: const LatLng(37.53774689, 126.9643189),
  );

  Offset? _dragStart;
  double _scaleData = 1.0;

  // 터치하는 순간만 실행, 드래그 해도 최초 터치 지점을 표시,
  _scaleStart(ScaleStartDetails details) {
    _dragStart = details.focalPoint;
    _scaleData = 1.0;
    debugPrint('_scaleStart ${_dragStart.toString()} / ${details.toString()}');
  }

  // 드레그 하는 동안 계속 실행됨,
  _scaleUpdate(ScaleUpdateDetails details, MapTransformer transformer) {
    var _scaleDiff = details.scale - _scaleData;
    _scaleData = details.scale;
    _mapController.zoom += _scaleDiff;

    if (_scaleDiff > 0) {
      _mapController.zoom += 0.02;
    } else if (_scaleDiff < 0) {
      _mapController.zoom -= 0.02;
    } else {
      final now = details.focalPoint;
      final diff = now - _dragStart!;
      _dragStart = now;
      transformer.drag(diff.dx, diff.dy);
    }
    setState(() {});
  }

  // 버전이 업데이트 되며서 변경된 위젯명, Map -> TileLayer, MapLayoutBuilder -> MapLayout
  @override
  Widget build(BuildContext context) {
    return MapLayout(
      builder: (context, transformer) {
        return GestureDetector(
          onScaleStart: _scaleStart,
          onScaleUpdate: (details) => _scaleUpdate(details, transformer),
          child: TileLayer(
            builder: (context, x, y, z) {
              //Google Maps
              final url =
                  'https://www.google.com/maps/vt/pb=!1m4!1m3!1i$z!2i$x!3i$y!2m3!1e0!2sm!3i420120488!3m7!2sen!5e1105!12m4!1e68!2m2!1sset!2sRoadmap!4e0!5m1!1e0!23i4111425';

              return ExtendedImage.network(
                url,
                fit: BoxFit.cover,
              );
            },
          ),
        );
      },
      controller: _mapController,
    );
  }
}

 

 

 

./src/screens/main_screen.dart - 

 

body: IndexedStack(
  index: _bottomSelectedIndex,
  children: <Widget>[
    const ItemsScreen(),
    const MapScreen(),
    Container(color: Colors.accents[1]),
    Container(color: Colors.accents[3]),
    Container(color: Colors.accents[5]),
    Container(color: Colors.accents[7]),
  ],
),