【问题标题】:How to add marker in the google map using flutter?如何使用颤振在谷歌地图中添加标记?
【发布时间】:2019-11-19 23:00:26
【问题描述】:

我正在创建一个附近的 Flutter 应用程序,它会显示您所在位置附近的餐厅。我找到了附近的位置,但无法在附近的坐标上添加标记。我想知道如何使用 google API 将标记添加到我的位置以及如何将位置从列表加载到我的地图。

void getData() async {
    http.Response response = await http.get(
        'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=1500&type=restaurant&key=API_KEY');

    if (response.statusCode == 200) {
      String data = response.body;
      var decodedData = jsonDecode(data);
      print(decodedData);
      List<String> names = [];
      List<double> lat = [];
      List<double> lng = [];
      for (var i = 0; i < 10; i++) {
        names.add(decodedData['results'][i]['name']);
        lat.add(decodedData['results'][i]['geometry']['location']['lat']);
        lng.add(decodedData['results'][i]['geometry']['location']['lng']);
      }
      print(names);
      print(lat);
      print(lng);
    }
  }



Expanded(
              child: Container(
                height: MediaQuery.of(context).size.height,
                width: MediaQuery.of(context).size.width,
                child: GoogleMap(
                  initialCameraPosition: CameraPosition(
                    target: LatLng(-33.8670522, 151.1957362),
                    zoom: 14.4746,
                  ),
                  markers: Set<Marker>.of(markers.values),
                  onMapCreated: (GoogleMapController controller) {
                    _controller.complete(controller);
                  },
                ),
              ),
            ),

【问题讨论】:

    标签: google-maps google-maps-api-3 flutter


    【解决方案1】:

    最后你必须自己构建它,但它应该看起来像这样

      final Set<Marker> _markers = {};
    
      setState(() {
      // add marker on the position
      _markers.add(Marker(
      // This marker id can be anything that uniquely identifies each marker.
      markerId: MarkerId(_lastMapPosition.toString()),
      position: _lastMapPosition,
      infoWindow: InfoWindow(
      // title is the address
      title: address.addressLine,
      // snippet are the coordinates of the position
      snippet: 'Lat: ${address.coordinates.latitude}, Lng: ${address
          .coordinates.longitude}',
      ),
      icon: BitmapDescriptor.defaultMarker,
      ));
      }
    

    【讨论】:

      【解决方案2】:

      确保添加您的API_KEY。以下是您要求的工作示例

      import 'package:flutter/material.dart';
      import 'package:google_maps_flutter/google_maps_flutter.dart';
      import 'package:http/http.dart' as http;
      import 'dart:convert';
      
      void main() => runApp(MyApp());
      
      class MyApp extends StatelessWidget {
        // This widget is the root of your application.
        @override
        Widget build(BuildContext context) {
          return MaterialApp(
            title: 'Flutter Demo',
            theme: ThemeData(
              primarySwatch: Colors.blue,
            ),
            home: MyHomePage(title: 'Flutter Demo Home Page'),
          );
        }
      }
      
      class MyHomePage extends StatefulWidget {
        MyHomePage({Key key, this.title}) : super(key: key);
      
        final String title;
      
        @override
        _MyHomePageState createState() => _MyHomePageState();
      }
      
      class _MyHomePageState extends State<MyHomePage> {
        LatLng latlng = LatLng(
          -33.8670522,
          151.1957362,
        );
        Iterable markers = [];
      
        @override
        void initState() {
          super.initState();
      
          getData();
        }
      
        getData() async {
          try {
            final response =
                await http.get('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=1500&type=restaurant&key=API_KEY');
      
            final int statusCode = response.statusCode;
      
            if (statusCode == 201 || statusCode == 200) {
              Map responseBody = json.decode(response.body);
              List results = responseBody["results"];
      
              Iterable _markers = Iterable.generate(10, (index) {
                Map result = results[index];
                Map location = result["geometry"]["location"];
                LatLng latLngMarker = LatLng(location["lat"], location["lng"]);
      
                return Marker(markerId: MarkerId("marker$index"),position: latLngMarker);
              });
      
              setState(() {
                markers = _markers;
              });
            } else {
              throw Exception('Error');
            }
          } catch(e) {
            print(e.toString());
          }
        }
      
        @override
        Widget build(BuildContext context) {
      
          return Scaffold(
            appBar: AppBar(
              title: Text(widget.title),
            ),
            body: GoogleMap(
              markers: Set.from(
                markers,
              ),
              initialCameraPosition: CameraPosition(target: latlng, zoom: 15.0),
              mapType: MapType.hybrid,
              onMapCreated: (GoogleMapController controller) {},
            ),
          );
        }
      }
      
      

      【讨论】:

      • 像魅力一样工作,顺便说一句,我还有一个与同一个应用程序有关的问题,所以如果你喜欢,请去看看。感谢您的回答。
      • 太棒了!喜欢这种类型的答案:),干净且充分解释
      【解决方案3】:
      Iterable markers = [];
      
      // in GoogleMap use like this
      
      GoogleMap(...
        markers: Set.from(markers),
      ),
      
      // in function or where you want
      
      Iterable _markers = Iterable.generate(list.length, (index) {
      return Marker(
        markerId: MarkerId("marker$index"),
        position: list[index].position);
      });
      setState(() {
        markers = _markers;
      });
      

      【讨论】:

      • 虽然这段代码可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因
      猜你喜欢
      • 2021-07-13
      • 2020-03-14
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 2019-06-30
      • 1970-01-01
      • 2020-07-19
      • 2019-09-23
      相关资源
      最近更新 更多