Flutter地图位置搜索插件mapmyindia_place_widget的使用

发布于 1周前 作者 phonegap100 来自 Flutter

Flutter 地图位置搜索插件 mapmyindia_place_widget 的使用

简介

MapmyIndia 搜索小部件包含地址自动完成和地点选择器功能。

开始使用

在你的项目 pubspec.yaml 文件中添加以下依赖:

dependencies:  
  mapmyindia_place_widget: ^0.2.0

然后在 Dart 代码中导入这个包:

import 'package:mapmyindia_place_widget/mapmyindia_place_widget.dart'; 

添加 MapmyIndia 密钥

你必须通过 MapmyIndiaAccountManager 类提供你的密钥。具体操作可以参考 这里

地址自动完成

使用 openPlaceAutocomplete 方法打开地址自动完成功能:

// 平台消息可能会失败,因此我们使用 try/catch 处理 PlatformException。
try {  
  ELocation eLocation = await openPlaceAutocomplete(PlaceOptions(enableTextSearch: true, hint: "search Location"));  
  print(json.encode(eLocation.toJson()));  
} on PlatformException {  
  // 处理异常
}

你可以使用 PlaceOptions 设置小部件的属性:

  • filter(String): 用于限制结果范围,例如指定一个区域或某些特定的地点(如POI、地标等)。
  • hint(String): 设置搜索框中的提示信息。
  • historyCount(int): 最多显示的历史记录数量。
  • pod(String): 用于限制结果类型。
  • backgroundColor(String): 设置搜索框的背景颜色。
  • toolbarColor(String): 设置工具栏的颜色。
  • saveHistory(bool): 是否保存历史记录。
  • tokenizeAddress(bool): 是否解析地址。
  • zoom(double): 设置当前地图的缩放级别。
  • location(LatLng): 设置搜索中心点的位置。
  • attributionHorizontalAlignment(int): 设置 attribution 的水平对齐方式。
  • attributionVerticalAlignment(int): 设置 attribution 的垂直对齐方式。
  • logoSize(int): 设置 logo 的大小。

地点选择器

使用 openPlacePicker 方法打开地点选择器:

try {   
  Place place = await openPlacePicker(PickerOption(includeSearch: true));  
  print(json.encode(place.toJson()));  
} on PlatformException {  
  // 处理异常
}

你可以使用 PickerOption 设置小部件的属性:

  • includeDeviceLocationButton(bool): 启用或禁用当前位置功能。
  • includeSearch(bool): 提供搜索地点的功能。
  • mapMaxZoom(double): 设置地图的最大缩放级别。
  • mapMinZoom(double): 设置地图的最小缩放级别。
  • placeOptions(PlaceOptions): 设置搜索框的所有属性。
  • toolbarColor(String): 设置工具栏的颜色。
  • marker(Uint8List): 更改地图中心点的标记图像。
  • statingCameraPosition(CameraPosition): 设置地图的初始相机位置。
  • startingBounds(LatLngBounds): 设置地图的初始边界。

完整示例代码

以下是完整的示例代码:

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

void main() {
  runApp(MaterialApp(
    home: MyApp(),
    routes: <String, WidgetBuilder>{
      '/PlaceSearchWidget': (BuildContext context) => PlaceSearchWidget(),
      '/PlacePickerWidget': (BuildContext context) => PlacePickerWidget(),
    },
  ));
}

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

class _MyAppState extends State<MyApp> {

  static const String MAP_SDK_KEY = "your_map_sdk_key";
  static const String REST_API_KEY = "your_rest_api_key";
  static const String ATLAS_CLIENT_ID = "your_atlas_client_id";
  static const String ATLAS_CLIENT_SECRET = "your_atlas_client_secret";

  [@override](/user/override)
  void initState() {
    super.initState();

    MapmyIndiaAccountManager.setMapSDKKey(MAP_SDK_KEY);
    MapmyIndiaAccountManager.setRestAPIKey(REST_API_KEY);
    MapmyIndiaAccountManager.setAtlasClientId(ATLAS_CLIENT_ID);
    MapmyIndiaAccountManager.setAtlasClientSecret(ATLAS_CLIENT_SECRET);
  }

  // 打开地址自动完成功能
  openPlaceSearch(BuildContext context) {
    Navigator.pushNamed(context, '/PlaceSearchWidget');
  }

  // 打开地点选择器
  openPlacePicker(BuildContext context) {
    Navigator.pushNamed(context, '/PlacePickerWidget');
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('插件示例应用'),
      ),
      body: Center(
        child: Column(children: [
          SizedBox(height: 20),
          TextButton(
            onPressed: () => openPlaceSearch(context),
            child: Text("地址自动完成"),
          ),
          SizedBox(height: 20),
          TextButton(
            onPressed: () => openPlacePicker(context),
            child: Text("地点选择器"),
          ),
        ]),
      ),
    );
  }
}

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

1 回复

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


当然,以下是一个关于如何在Flutter应用中使用mapmyindia_place_widget插件进行地图位置搜索的示例代码。这个插件允许用户在地图上搜索地点,并获取相关位置信息。

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

dependencies:
  flutter:
    sdk: flutter
  mapmyindia_place_widget: ^最新版本号  # 请替换为实际可用的最新版本号

然后,运行flutter pub get来获取依赖。

接下来是完整的示例代码,展示了如何在Flutter应用中使用mapmyindia_place_widget进行位置搜索:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter MapMyIndia Place Widget Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MapMyIndiaPlaceWidgetDemo(),
    );
  }
}

class MapMyIndiaPlaceWidgetDemo extends StatefulWidget {
  @override
  _MapMyIndiaPlaceWidgetDemoState createState() => _MapMyIndiaPlaceWidgetDemoState();
}

class _MapMyIndiaPlaceWidgetDemoState extends State<MapMyIndiaPlaceWidgetDemo> {
  final TextEditingController _searchController = TextEditingController();
  String _selectedPlaceName = '';
  LatLng? _selectedLatLng;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('MapMyIndia Place Widget Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextField(
              controller: _searchController,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Search Place',
                suffixIcon: IconButton(
                  icon: Icon(Icons.search),
                  onPressed: () async {
                    // 打开位置搜索对话框
                    final result = await showPlacePicker(
                      context: context,
                      apiKey: 'YOUR_MAPMYINDIA_API_KEY', // 请替换为你的MapMyIndia API Key
                      initialSearch: _searchController.text,
                    );

                    if (result != null) {
                      setState(() {
                        _selectedPlaceName = result.name;
                        _selectedLatLng = result.latLng;
                      });
                    }
                  },
                ),
              ),
            ),
            SizedBox(height: 16),
            if (_selectedPlaceName.isNotEmpty)
              Text(
                'Selected Place: $_selectedPlaceName\nLatitude: ${_selectedLatLng?.latitude}, Longitude: ${_selectedLatLng?.longitude}',
                style: TextStyle(fontSize: 18),
              ),
          ],
        ),
      ),
    );
  }
}

注意事项:

  1. API Key:确保你已经从MapMyIndia获得了API Key,并将其替换到代码中的YOUR_MAPMYINDIA_API_KEY位置。
  2. 权限:在实际应用中,你可能需要在AndroidManifest.xmlInfo.plist中添加必要的权限和配置,以允许应用访问位置服务。
  3. 错误处理:在实际应用中,建议添加错误处理逻辑,例如处理API调用失败的情况。

这个示例展示了如何使用mapmyindia_place_widget插件在Flutter应用中实现一个简单的位置搜索功能。用户可以在文本框中输入搜索词,然后点击搜索图标来打开位置搜索对话框,选择地点后,会在界面上显示所选地点的名称和经纬度。

回到顶部