Flutter地点搜索与地图标记更新插件search_map_place_updated的使用

Flutter地点搜索与地图标记更新插件search_map_place_updated的使用

简介

search_map_place_updated 是一个Flutter插件,它使用Google Maps API创建了一个TextField,当用户输入时会尝试自动补全地点,并提供简洁平滑的动画效果,从而提升UI和UX体验。该插件还提供了关于用户选择地点的详细信息,如坐标、边界等,以便确定GoogleMap小部件的缩放级别。

示例

开始使用

安装

要安装此插件,请将其添加到 pubspec.yaml 文件中:

dependencies:
    search_map_place_updated: <latest>

确保在Google Cloud Platform中激活以下API:

  • Places
  • Geolocation
  • Geocoding

然后可以在您的应用程序中导入并使用此插件:

import 'package:search_map_place_updated/search_map_place_updated.dart';

使用方法

在您想要添加搜索小部件的地方调用 SearchMapPlaceWidget 的构造函数:

Widget build(BuildContext context) {
  return Scaffold(
    body: Center(
      child: SearchMapPlaceWidget(
        apiKey: // 您的Google Maps API密钥
      )
    )
  );
}

SearchMapPlaceWidget 的构造函数有7个与API相关的属性:

  • String apiKey:唯一必需的属性,是您的应用程序使用的Google Maps API密钥。
  • (Place) void onSelected:当用户选择其中一个自动补全选项时调用的回调函数。
  • (Place) void onSearch:当用户点击搜索图标时调用的回调函数。
  • String language:用于自动补全的语言,默认为’en’(英语)。支持的语言列表请参考Google Maps API文档。
  • LatLng location:您希望检索地点信息的中心点。如果提供了此值,则必须同时提供 radius
  • int radius:返回地点结果的距离(以米为单位)。请注意,设置半径会偏向指定区域的结果,但可能不会完全限制结果在指定区域内。如果提供了此值,则必须同时提供 location
  • bool restrictBounds:仅返回严格位于由 locationradius 定义的区域内的地点。
  • PlaceType placeType:允许您通过类型过滤地点。有关可用类型的更多信息,请参考Google Maps API文档。默认情况下,不传递任何过滤器,这意味着所有地点类型都将在自动补全中显示。

Place类

Place 类会在 onSelectedonSearch 方法中返回,它允许我们获取更多关于用户选择地点的信息。

最初,它只提供基本的信息:

  • description:包含返回结果的人类可读名称。对于企业结果,这通常是企业名称。
  • placeId:唯一标识地点的文本ID。有关地点ID的更多信息,请参阅Google Maps API文档。
  • types:包含适用于该地点的类型数组。数组可以包含多个值。有关地点类型的更多信息,请参阅Google Maps API文档。
  • fullJSON:包含从Places API接收到的完整JSON响应。可以用于提取额外信息。有关更多信息,请参阅Google Places Autocomplete API文档。

您可以通过调用以下代码获取更多关于地点的信息,如坐标和边界:

await myPlace.geolocation;

示例代码

以下是一个完整的示例代码,展示了如何使用 SearchMapPlaceWidget 小部件:

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:search_map_place_updated/search_map_place_updated.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MapScreen(),
    );
  }
}

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

class _MapScreenState extends State<MapScreen> {
  final Completer<GoogleMapController> _mapController = Completer();

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('地点搜索与地图标记更新'),
      ),
      body: Stack(
        children: [
          GoogleMap(
            initialCameraPosition: CameraPosition(
              target: LatLng(37.4219999, -122.0840575),
              zoom: 14.4746,
            ),
            onMapCreated: (GoogleMapController controller) {
              _mapController.complete(controller);
            },
          ),
          Positioned(
            top: 20,
            left: 20,
            right: 20,
            child: SearchMapPlaceWidget(
              apiKey: 'YOUR_API_KEY', // 替换为您的Google Maps API密钥
              language: 'zh',
              location: LatLng(37.4219999, -122.0840575), // 用户位置
              radius: 30000, // 半径为30公里
              onSelected: (Place place) async {
                final geolocation = await place.geolocation;

                // 动画移动GoogleMap相机到选定位置,并适当缩放
                final GoogleMapController controller = await _mapController.future;
                controller.animateCamera(CameraUpdate.newLatLng(geolocation.coordinates));
                controller.animateCamera(CameraUpdate.newLatLngBounds(geolocation.bounds, 0));
              },
            ),
          ),
        ],
      ),
    );
  }
}

更多关于Flutter地点搜索与地图标记更新插件search_map_place_updated的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter地点搜索与地图标记更新插件search_map_place_updated的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用 search_map_place_updated 插件来实现 Flutter 应用中的地点搜索与地图标记更新的示例代码。

首先,确保你已经在 pubspec.yaml 文件中添加了 search_map_place_updated 插件的依赖项:

dependencies:
  flutter:
    sdk: flutter
  search_map_place: ^最新版本号  # 请替换为最新版本号
  google_maps_flutter: ^最新版本号  # 请替换为最新版本号

然后,运行 flutter pub get 来安装依赖项。

接下来是示例代码,它展示了如何使用 search_map_place_updated 插件来搜索地点并在 Google 地图上标记这些地点:

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:search_map_place/search_map_place.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MapScreen(),
    );
  }
}

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

class _MapScreenState extends State<MapScreen> {
  Completer<GoogleMapController> _controller = Completer();
  Set<Marker> _markers = Set<Marker>();
  LatLng _center = LatLng(37.7749, -122.4194); // 初始中心位置,例如旧金山
  TextEditingController _searchController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('地点搜索与地图标记'),
      ),
      body: Column(
        children: <Widget>[
          Container(
            height: 50,
            decoration: BoxDecoration(
              color: Colors.grey[200],
              borderRadius: BorderRadius.circular(10),
            ),
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: TextField(
                controller: _searchController,
                decoration: InputDecoration(
                  border: InputBorder.none,
                  hintText: '搜索地点',
                  suffixIcon: IconButton(
                    icon: Icon(Icons.search),
                    onPressed: _onSearchPressed,
                  ),
                ),
              ),
            ),
          ),
          Expanded(
            child: GoogleMap(
              mapType: MapType.normal,
              initialCameraPosition: CameraPosition(
                target: _center,
                zoom: 14.0,
              ),
              markers: _markers,
              onMapCreated: (GoogleMapController controller) {
                _controller.complete(controller);
              },
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _onSearchPressed() async {
    String searchResult = _searchController.text;
    if (searchResult.isEmpty) return;

    List<Prediction> predictions = await PlacesAutocomplete.show(
      context: context,
      apiKey: 'YOUR_GOOGLE_MAPS_PLACES_API_KEY', // 请替换为你的 Google Maps Places API Key
      mode: Mode.overlay,
      language: "en",
    );

    if (predictions != null && predictions.isNotEmpty) {
      Prediction firstPrediction = predictions.first;
      String placeId = firstPrediction.placeId;

      PlaceDetails placeDetails = await Places.getDetailsByPlaceId(placeId, apiKey: 'YOUR_GOOGLE_MAPS_PLACES_API_KEY');

      LatLng latLng = LatLng(
        placeDetails.geometry!.location.lat!,
        placeDetails.geometry!.location.lng!,
      );

      setState(() {
        _markers.clear();
        _markers.add(Marker(
          markerId: MarkerId(placeDetails.name!),
          position: latLng,
          infoWindow: InfoWindow(title: placeDetails.name, snippet: placeDetails.vicinity),
        ));
        _center = latLng;
      });

      _controller.future?.animateCamera(CameraUpdate.newLatLngZoom(_center, 16));
    }
  }
}

在这个示例中,我们做了以下几件事情:

  1. UI布局:使用 ScaffoldAppBarColumn 布局了一个简单的搜索栏和地图视图。
  2. 搜索栏:使用 TextFieldTextEditingController 来处理用户输入的搜索地点。
  3. 地点搜索:通过 PlacesAutocomplete.show 方法来显示地点搜索下拉列表,当用户选择一个地点时,获取该地点的详细信息。
  4. 地图标记:使用 GoogleMapMarker 来在地图上标记搜索到的地点,并更新地图的中心位置。

请注意,你需要在代码中替换 'YOUR_GOOGLE_MAPS_PLACES_API_KEY' 为你自己的 Google Maps Places API Key。

希望这个示例代码对你有帮助!

回到顶部