Flutter地图服务插件neom_maps_services的使用

Flutter 地图服务插件 neom_maps_services 的使用

通用信息

这是一个用于 Google 地图服务的 Dart 库。你可以在这里找到 Google 地图平台文档,但如果你是新手,可以从这里开始:Google 地图入门指南

API 密钥

要使用此库,你需要一个 Web API 密钥。请按照以下步骤获取与你的 Dart 应用程序相关的密钥:获取 Places Web 服务 API 密钥

这些密钥不能单独作为 Android 或 iOS API 密钥使用,而是应该在你的 Dart 应用程序中使用。

可用的 API

使用方法

Geocoding

import "package:google_maps_webservice/geocoding.dart";

final geocoding = GoogleMapsGeocoding(apiKey: "<API_KEY>");
final geocoding = GoogleMapsGeocoding(apiKey: "<API_KEY>", httpClient: BrowserClient());
final geocoding = GoogleMapsGeocoding(baseUrl: "http://myProxy.com");

// 搜索地址
GeocodingResponse response = await geocoding.searchByAddress("1600 Amphitheatre Parkway, Mountain View, CA");

Places

import "package:google_maps_webservice/places.dart";

final places = GoogleMapsPlaces(apiKey: "<API_KEY>");
final places = GoogleMapsPlaces(apiKey: "<API_KEY>", httpClient: BrowserClient());
final places = GoogleMapsPlaces(baseUrl: "http://myProxy.com");

// 搜索附近的地点
PlacesSearchResponse response = await places.searchNearbyWithRadius(Location(lat: 31.0424, lng: 42.421), 500);

// 按距离排序搜索附近的地点
PlacesSearchResponse response = await places.searchNearbyWithRankby(Location(lat: 31.0424, lng: 42.421), "distance");

// 搜索特定文本
PlacesSearchResponse response = await places.searchByText("123 Main Street");

// 获取地点详细信息
PlacesDetailsResponse response = await places.getDetailsByPlaceId("PLACE_ID");
PlacesDetailsResponse response = await places.getDetailsByReference("REF");

Timezone

import "package:google_maps_webservice/timezone.dart";

final timezone = GoogleMapsTimezone(apiKey: "<API_KEY>");
final timezone = GoogleMapsTimezone(apiKey: "<API_KEY>", httpClient: BrowserClient());
final timezone = GoogleMapsTimezone(baseUrl: "http://myProxy.com");

// 获取指定位置的时区信息
TimezoneResponse response = await timezone.getByLocation(Location(lat: 31.0424, lng: 42.421));

// 获取指定位置和时间戳的时区信息
TimezoneResponse response = await timezone.getByLocation(Location(lat: 31.0424, lng: 42.421), timestamp: DateTime.utc(2019, 4, 24));

// 获取指定位置、时间戳和语言的时区信息
TimezoneResponse response = await timezone.getByLocation(Location(lat: 31.0424, lng: 42.421), timestamp: DateTime.utc(2019, 4, 24), language: 'es');

Static Map

import "package:google_maps_webservice/staticmaps.dart";

final mapStatic = StaticMap(
  apiKey,
  markers: List.from([
    Location(lat: 23.721160, lng: 90.394435),
    Location(lat: 23.732322, lng: 90.385142),
  ]),
  path: Path(
    enc: 'svh~F`j}uOusC`bD', // 编码后的路径
    color: 'black',
  ),
  scale: 'false' // 是否缩放
);

String url = mapStatic.getUrl();

Image.network(url)

代理

如果需要通过代理服务器使用该库,可以通过设置 baseUrl 来实现。如果代理服务器已经设置了 apiKey,则无需在应用中存储 apiKey。(不在应用中存储 apiKey 是一种良好的实践)

完整示例

Directions API

import 'package:flutter/material.dart';
import 'package:google_maps_webservice/src/core.dart';
import 'package:google_maps_webservice/src/directions.dart';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Directions Example')),
        body: DirectionsExample(),
      ),
    );
  }
}

class DirectionsExample extends StatefulWidget {
  [@override](/user/override)
  _DirectionsExampleState createState() => _DirectionsExampleState();
}

class _DirectionsExampleState extends State<DirectionsExample> {
  late GoogleMapsDirections directions;
  late Future<DirectionsResult> futureDirections;

  [@override](/user/override)
  void initState() {
    super.initState();
    final googleMaps = GoogleMapsDirections(apiKey: "<API_KEY>");
    directions = googleMaps;
    futureDirections = getDirections();
  }

  Future<DirectionsResult> getDirections() async {
    return await directions.query(
      origin: Location(lat: 37.361764, lng: -122.020398),
      destination: Location(lat: 37.365524, lng: -122.025129),
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return FutureBuilder<DirectionsResult>(
      future: futureDirections,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          final result = snapshot.data!;
          return Column(
            children: [
              Text(result.status),
              Expanded(
                child: ListView.builder(
                  itemCount: result.routes?.length ?? 0,
                  itemBuilder: (context, index) {
                    final route = result.routes![index];
                    return ListTile(
                      title: Text(route.summary ?? ''),
                      subtitle: Text(route.distance.text ?? ''),
                    );
                  },
                ),
              ),
            ],
          );
        } else if (snapshot.hasError) {
          return Center(child: Text(snapshot.error.toString()));
        }
        return Center(child: CircularProgressIndicator());
      },
    );
  }
}

Places API

import 'package:flutter/material.dart';
import 'package:google_maps_webservice/src/places.dart';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Places Example')),
        body: PlacesExample(),
      ),
    );
  }
}

class PlacesExample extends StatefulWidget {
  [@override](/user/override)
  _PlacesExampleState createState() => _PlacesExampleState();
}

class _PlacesExampleState extends State<PlacesExample> {
  late GoogleMapsPlaces places;
  late Future<PlacesSearchResponse> futurePlaces;

  [@override](/user/override)
  void initState() {
    super.initState();
    places = GoogleMapsPlaces(apiKey: "<API_KEY>");
    futurePlaces = searchNearby();
  }

  Future<PlacesSearchResponse> searchNearby() async {
    return await places.searchNearbyWithRankby(
      Location(lat: 37.361764, lng: -122.020398),
      "distance",
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return FutureBuilder<PlacesSearchResponse>(
      future: futurePlaces,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          final result = snapshot.data!;
          return ListView.builder(
            itemCount: result.results?.length ?? 0,
            itemBuilder: (context, index) {
              final place = result.results![index];
              return ListTile(
                title: Text(place.name ?? ''),
                subtitle: Text(place.vicinity ?? ''),
              );
            },
          );
        } else if (snapshot.hasError) {
          return Center(child: Text(snapshot.error.toString()));
        }
        return Center(child: CircularProgressIndicator());
      },
    );
  }
}

Timezone API

import 'package:flutter/material.dart';
import 'package:google_maps_webservice/src/timezone.dart';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Timezone Example')),
        body: TimezoneExample(),
      ),
    );
  }
}

class TimezoneExample extends StatefulWidget {
  [@override](/user/override)
  _TimezoneExampleState createState() => _TimezoneExampleState();
}

class _TimezoneExampleState extends State<TimezoneExample> {
  late GoogleMapsTimezone timezone;
  late Future<TimezoneResponse> futureTimezone;

  [@override](/user/override)
  void initState() {
    super.initState();
    timezone = GoogleMapsTimezone(apiKey: "<API_KEY>");
    futureTimezone = getTimezone();
  }

  Future<TimezoneResponse> getTimezone() async {
    return await timezone.getByLocation(
      Location(lat: 37.361764, lng: -122.020398),
      timestamp: DateTime.utc(2019, 4, 24),
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return FutureBuilder<TimezoneResponse>(
      future: futureTimezone,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          final result = snapshot.data!;
          return Center(
            child: Text(result.timeZoneId ?? ''),
          );
        } else if (snapshot.hasError) {
          return Center(child: Text(snapshot.error.toString()));
        }
        return Center(child: CircularProgressIndicator());
      },
    );
  }
}

Static Map API

import 'package:flutter/material.dart';
import 'package:google_maps_webservice/src/staticmaps.dart';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Static Map Example')),
        body: StaticMapExample(),
      ),
    );
  }
}

class StaticMapExample extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    final mapStatic = StaticMap(
      apiKey,
      markers: List.from([
        Location(lat: 23.721160, lng: 90.394435),
        Location(lat: 23.732322, lng: 90.385142),
      ]),
      path: Path(
        enc: 'svh~F`j}uOusC`bD',
        color: 'black',
      ),
      scale: 'false',
    );

    final url = mapStatic.getUrl();

    return Center(
      child: Image.network(url),
    );
  }
}

更多关于Flutter地图服务插件neom_maps_services的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter地图服务插件neom_maps_services的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用neom_maps_services插件的示例代码。这个插件通常用于集成Neom Maps服务,包括地图显示、位置搜索等功能。

首先,确保你的Flutter环境已经设置好,并且你的项目已经创建。接下来,你需要添加neom_maps_services插件到你的pubspec.yaml文件中:

dependencies:
  flutter:
    sdk: flutter
  neom_maps_services: ^最新版本号 # 请替换为最新的版本号

然后运行flutter pub get来安装插件。

以下是一个简单的示例,展示如何在Flutter应用中使用neom_maps_services插件来显示一个地图,并执行一个简单的位置搜索。

1. 主应用代码(main.dart)

import 'package:flutter/material.dart';
import 'package:neom_maps_services/neom_maps_services.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Neom Maps Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MapScreen(),
    );
  }
}

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

class _MapScreenState extends State<MapScreen> {
  NeomMapsController? _controller;

  @override
  void initState() {
    super.initState();
    _initializeMap();
  }

  Future<void> _initializeMap() async {
    // 初始化Neom Maps控制器
    _controller = NeomMapsController(
      apiKey: 'YOUR_NEOM_MAPS_API_KEY', // 请替换为你的Neom Maps API密钥
      onMapCreated: (NeomMapsController controller) {
        // 地图创建成功后的回调
        controller.moveCamera(
          CameraUpdate.newLatLngZoom(
            LatLng(24.684897, 39.907498), // 初始中心点坐标(例如:利雅得)
            12.0,
          ),
        );
      },
    );

    // 加载地图
    WidgetsBinding.instance!.addPostFrameCallback((_) async {
      await _controller!.onMapReady();
      // 示例:搜索位置
      _searchLocation('Riyadh');
    });
  }

  Future<void> _searchLocation(String locationName) async {
    final List<PlacePrediction> predictions = await PlacesAutocomplete.show(
      context: context,
      apiKey: 'YOUR_GOOGLE_MAPS_PLACES_API_KEY', // 请替换为你的Google Maps Places API密钥
      mode: Mode.overlay,
      language: "ar", // 可选:设置搜索语言
    );

    if (predictions.isNotEmpty) {
      final PlacePrediction firstPrediction = predictions.first;
      // 获取预测结果的地理位置
      final GeocodingResult? result = await Geolocator.placemarkFromAddress(firstPrediction.description!);

      if (result != null && result.placemarks.isNotEmpty) {
        final LatLng location = LatLng(result.placemarks.first.coordinates!.latitude, result.placemarks.first.coordinates!.longitude);
        _controller!.moveCamera(CameraUpdate.newLatLngZoom(location, 15.0));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Neom Maps Example'),
      ),
      body: NeomMapView(
        controller: _controller!,
        options: MapOptions(
          // 地图选项配置
          mapType: MapType.normal,
          initialCameraPosition: CameraPosition(
            target: LatLng(24.684897, 39.907498), // 初始中心点坐标
            zoom: 12.0,
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _searchLocation('Riyadh'), // 示例:搜索利雅得
        tooltip: 'Search Location',
        child: Icon(Icons.search),
      ),
    );
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }
}

注意事项

  1. API密钥:你需要替换YOUR_NEOM_MAPS_API_KEYYOUR_GOOGLE_MAPS_PLACES_API_KEY为你自己的API密钥。
  2. 权限:确保你的Android和iOS项目已经配置了必要的权限(如访问网络、位置信息等)。
  3. 依赖neom_maps_services可能还依赖于其他包(如geolocator),请确保在你的pubspec.yaml文件中添加这些依赖。

这个示例展示了如何初始化Neom Maps,并在地图上显示一个初始位置。同时,它还演示了如何使用Google Maps Places API进行位置搜索,并将搜索结果显示在地图上。根据你的具体需求,你可以进一步扩展和修改这个示例。

回到顶部