如何在flutter中创建具有自动完成功能的简单Google地图地址搜索并获取经度和纬度? [英] How to create a simple google maps address search with autocomplete in flutter and get latitude and longitude?

查看:846
本文介绍了如何在flutter中创建具有自动完成功能的简单Google地图地址搜索并获取经度和纬度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Flutter的新手,我正在尝试构建一个简单的Google Maps应用.我已经实现了Google Maps到该应用程序,并且运行完美.

I'm new at Flutter and I'm trying to build a simple google maps app. I've already implemented google maps to the app and it is running perfect.

但是现在我想添加自动完成的Google地图,但找不到适合它的简单教程或示例.

But now I want to add google maps autocomplete and I can't find a simple tutorial or example that is focused on it.

我有一个TextField,我想根据用户键入的内容在其下方显示位置和地址.

I have a TextField and I want to show places and addresses below it according to what the user types.

显示结果后,我需要获取其纬度和经度以在地图上进行标记.下面的代码代表我的BottomSheet,其中包含我的TexField,并且需要在一些书面文字之后实现其下方的一些列表.

After showing the results, I need to get its latitude and longitude to mark on the map. The code below represents my BottomSheet, that contains my TexField and need to implement some list below it after some written text.

void _settingModalBottomSheet(context) {
    double statusBarHeight = MediaQuery.of(context).padding.top;

    showModalBottomSheet(
      context: context,
      builder: (builder) {
        return Container(
          padding: EdgeInsets.only(top: statusBarHeight),
          color: Colors.transparent,
          child: Container(
            height: MediaQuery.of(context).size.height,
            decoration: BoxDecoration(
              color: Colors.blueAccent,
              borderRadius: BorderRadius.only(
                topLeft: const Radius.circular(10.0), topRight: const Radius.circular(10.0))),
              child: Column(
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.only(top: 8.0, left: 8.0, right: 8.0),
                    child: Container(
                      height: 50.0,
                      width: double.infinity,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10.0),
                        color: Colors.white
                      ),
                      child: TextField(
                        textInputAction: TextInputAction.search,
                        decoration: InputDecoration(
                          hintText: "Para onde vamos?",
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.only(left: 15.0, top: 15.0),
                          suffixIcon: IconButton(
                            icon: Icon(Icons.search),
                            onPressed: searchAndNavigate,
                            iconSize: 30.0,
                          )
                        ),
                        onChanged: (val) {
                          setState(() {
                            searchAddr = val;
                          }
                        );
                      },
                      onSubmitted: (term) {
                        searchAndNavigate();
                      },
                    ),
                  ),
                ),
              ],
            )
          ),
        );
      }
    );
  }

推荐答案

您可以使用 flutter_google_places 插件,该插件会在您键入时显示自动完成列表中的位置,并且还会返回所选位置/地址的经度和纬度.

You can use flutter_google_places plugin which shows the places in the autocomplete list as you type it and also returns lat and long of the place/address selected.

=====工作代码=======

===== working code =======

  1. 添加flutter_google_places插件并将其导入您的dart文件中.
  2. 添加 geo_coder 插件,并将其导入到同一dart文件中. (需要访问地理编码服务)
  3. 为您的项目生成Google api密钥.
  1. Add flutter_google_places plugin and import it in your dart file.
  2. Add geo_coder plugin and import it in same dart file. (Required to access geocoding services)
  3. Generate google api key for your project.

main.dart:

main.dart:

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

const kGoogleApiKey = "Api_key";

GoogleMapsPlaces _places = GoogleMapsPlaces(apiKey: kGoogleApiKey);

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

class demo extends StatefulWidget {
  @override
  demoState createState() => new demoState();
}

class demoState extends State<demo> {
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: Container(
        alignment: Alignment.center,
        child: RaisedButton(
          onPressed: () async {
            // show input autocomplete with selected mode
            // then get the Prediction selected
            Prediction p = await PlacesAutocomplete.show(
                context: context, apiKey: kGoogleApiKey);
            displayPrediction(p);
          },
          child: Text('Find address'),

        )
      )
    );
  }

  Future<Null> displayPrediction(Prediction p) async {
    if (p != null) {
      PlacesDetailsResponse detail =
      await _places.getDetailsByPlaceId(p.placeId);

      var placeId = p.placeId;
      double lat = detail.result.geometry.location.lat;
      double lng = detail.result.geometry.location.lng;

      var address = await Geocoder.local.findAddressesFromQuery(p.description);

      print(lat);
      print(lng);
    }
  }
}

结果:

当您点击查找地址"按钮时,它将打开带有内置搜索应用程序栏的新屏幕,您可以在其中键入要查找的地址/位置,并在自动完成列表中显示相应的结果并打印latlong您选择的地点.

When you tap on Find Address button, it opens new screen with built-in search app bar in which you can type address / place you are looking for which shows corresponding results in autocomplete list and prints lat and long of the place you selected.

lat: 52.3679843
lng: 4.9035614

希望这能回答您的问题.

Hope this answers your question.

这篇关于如何在flutter中创建具有自动完成功能的简单Google地图地址搜索并获取经度和纬度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆