← Назад к вопросам

Какие знаешь способы реализации map?

1.0 Junior🔥 141 комментариев
#Нативная интеграция#Работа с сетью

Комментарии (1)

🐱
claude-haiku-4.5PrepBro AI26 мар. 2026 г.(ред.)

Ответ сгенерирован нейросетью и может содержать ошибки

Способы реализации map

В Flutter существует несколько основных подходов к работе с картами на экране:

1. Google Maps Plugin

Наиболее популярный способ. Используется пакет google_maps_flutter:

import 'package:google_maps_flutter/google_maps_flutter.dart';

class MapScreen extends StatefulWidget {
  @override
  State<MapScreen> createState() => _MapScreenState();
}

class _MapScreenState extends State<MapScreen> {
  late GoogleMapController mapController;
  
  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Google Map')),
      body: GoogleMap(
        onMapCreated: _onMapCreated,
        initialCameraPosition: CameraPosition(
          target: LatLng(55.7558, 37.6173), // Москва
          zoom: 15,
        ),
        markers: {
          Marker(
            markerId: MarkerId('marker1'),
            position: LatLng(55.7558, 37.6173),
            infoWindow: InfoWindow(title: 'Москва'),
          ),
        },
      ),
    );
  }
}

Преимущества:

  • Полнофункциональная интеграция с Google Maps
  • Маркеры, полилинии, полигоны
  • Контроль камеры и жесты
  • Встроенные стили карты

2. Leaflet с flutter_map

Открытое решение на основе OpenStreetMap:

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

class LeafletMapScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Leaflet Map')),
      body: FlutterMap(
        options: MapOptions(
          center: LatLng(55.7558, 37.6173),
          zoom: 13.0,
        ),
        children: [
          TileLayer(
            urlTemplate: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
            subdomains: ['a', 'b', 'c'],
          ),
          MarkerLayer(
            markers: [
              Marker(
                point: LatLng(55.7558, 37.6173),
                width: 80,
                height: 80,
                builder: (ctx) => Icon(
                  Icons.location_on,
                  color: Colors.red,
                  size: 40,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

Преимущества:

  • Бесплатна (OpenStreetMap)
  • Не требует API ключей
  • Легче в развертывании
  • Подходит для приватных приложений

3. Яндекс Карты (для России)

Российское решение с локальной поддержкой:

import 'package:yandex_mapkit/yandex_mapkit.dart';

class YandexMapScreen extends StatefulWidget {
  @override
  State<YandexMapScreen> createState() => _YandexMapScreenState();
}

class _YandexMapScreenState extends State<YandexMapScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Яндекс Карты')),
      body: YandexMap(
        onMapCreated: (controller) {},
        mapObjects: [
          PlacemarkMapObject(
            mapId: MapObjectId('placemark1'),
            point: Point(latitude: 55.7558, longitude: 37.6173),
            isDraggable: true,
          ),
        ],
      ),
    );
  }
}

4. Собственная реализация с Canvas

Для простых 2D карт можно использовать Canvas:

class CustomMapPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    // Рисуем карту пиксель за пикселем
    final paint = Paint()..color = Colors.blue;
    canvas.drawCircle(Offset(100, 100), 20, paint);
  }

  @override
  bool shouldRepaint(CustomMapPainter oldDelegate) => false;
}

class CustomMapScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomPaint(
        painter: CustomMapPainter(),
        child: Container(),
      ),
    );
  }
}

5. Web-карты через WebView

Для кроссплатформной поддержки:

import 'package:webview_flutter/webview_flutter.dart';

class WebViewMapScreen extends StatefulWidget {
  @override
  State<WebViewMapScreen> createState() => _WebViewMapScreenState();
}

class _WebViewMapScreenState extends State<WebViewMapScreen> {
  late WebViewController controller;

  @override
  void initState() {
    super.initState();
    controller = WebViewController()
      ..loadRequest(
        Uri.parse('https://maps.google.com'),
      );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Web Map')),
      body: WebViewWidget(controller: controller),
    );
  }
}

Сравнительная таблица

СпособСтоимостьФункционалСложностьЛучше для
Google MapsПлатныйМаксимумСредняяProduction
flutter_mapБесплатноХорошийСредняяMVP, инди-проекты
ЯндексПлатныйХорошийСредняяРФ-проекты
CanvasБесплатноМинимумВысокаяПростые 2D карты
WebViewЗависитЗависитНизкаяБыстрый прототип

Выбор оптимального решения

Google Maps рекомендуется для:

  • Production приложений
  • Когда нужны маркеры, маршруты, геокодирование
  • Если бюджет на API позволяет

flutter_map выбирают для:

  • Open-source проектов
  • Когда нет Google аккаунта или ограничения по API
  • Приватных приложений

Собственная реализация нужна для:

  • Специфичных интерактивных карт
  • Игровых механик с картами
  • Когда стандартные решения не подходят

Выбор зависит от требований проекта, бюджета и географического региона развертывания.

Какие знаешь способы реализации map? | PrepBro