用户如何在谷歌地图颤振上添加多个标记

Posted

技术标签:

【中文标题】用户如何在谷歌地图颤振上添加多个标记【英文标题】:How can user add multiple marker on google maps flutter 【发布时间】:2020-03-14 13:43:54 【问题描述】:

当用户长按地图时,用户如何添加多个标记。在这段代码中,我完成了单张地图。当用户在地图上长按时,它会自动添加一个标记,但我不知道如何在地图上添加多个标记。我尝试了很多代码,但没有得到正确的结果。希望你理解这个问题。你的小帮助可以让我开心。提前致谢。

这是我尝试过的代码:)

import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart';
import 'dart:async';

import 'package:google_maps_flutter/google_maps_flutter.dart';

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

const kGoogleApiKey = "API_KEY";

class MyApp extends StatelessWidget 
  @override
  Widget build(BuildContext context) 
    return MaterialApp(title: "MAP", home: BspAddressmapscreen());
  


class BspAddressmapscreen extends StatefulWidget 
  BspAddressmapscreen(Key key) : super(key: key);

  @override
  _BspAddressmapscreenState createState() => _BspAddressmapscreenState();


class _BspAddressmapscreenState extends State<BspAddressmapscreen> 
  final homeScaffoldKey = GlobalKey<ScaffoldState>();
  Completer<GoogleMapController> _controller = Completer();

  @override
  void initState() 
    super.initState();
  

  double zoomVal = 5.0;

  @override
  Widget build(BuildContext context) 
    return new Scaffold(
      appBar: AppBar(
        leading: IconButton(
            icon: Icon(Icons.arrow_back_ios),
            onPressed: () 
              /*NavigationHelper.navigatetoBack(context);*/
            ),
        centerTitle: true,
        title: Text("Business Address Detail"),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.search),
            onPressed: () ,
          ),
        ],
      ),
      bottomNavigationBar: Container(
        color: Colors.transparent,
        height: 56,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            new FlatButton.icon(
              icon: Icon(Icons.arrow_back_ios),
              label: Text('Show Address'),
              textColor: Colors.blue,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(7),
              ),
              onPressed: () 
                getUserLocation();
              ,
            ),
          ],
        ),
      ),
      body: Container(
        height: double.infinity,
        width: double.infinity,
        child: Stack(
          children: <Widget>[
            _searchbar(),
            _buildGoogleMap(context),
            _zoomminusfunction(),
            _zoomplusfunction(),
          ],
        ),
      ),
    );
  

  getUserLocation() async 
    markers.values.forEach((value) async 
      print(value.position);
      // From coordinates
      final coordinates =
          new Coordinates(value.position.latitude, value.position.longitude);
      var addresses = await Geocoder.google(kGoogleApiKey)
          .findAddressesFromCoordinates(coordinates);

      print("Address: $addresses.first.featureName");
      print("Address: $addresses.first.adminArea");
    );
  

  Future<void> _minus(double zoomVal) async 
    final GoogleMapController controller = await _controller.future;
    controller.animateCamera(CameraUpdate.newCameraPosition(
        CameraPosition(target: LatLng(40.712776, -74.005974), zoom: zoomVal)));
  

  Future<void> _plus(double zoomVal) async 
    final GoogleMapController controller = await _controller.future;
    controller.animateCamera(CameraUpdate.newCameraPosition(
        CameraPosition(target: LatLng(40.712776, -74.005974), zoom: zoomVal)));
  

  Map<MarkerId, Marker> markers = <MarkerId, Marker>;

  Widget _buildGoogleMap(BuildContext context) 
    return Container(
      height: MediaQuery.of(context).size.height,
      width: MediaQuery.of(context).size.width,
      child: GoogleMap(
        mapType: MapType.normal,
        initialCameraPosition:
            CameraPosition(target: LatLng(40.712776, -74.005974), zoom: 12),
        onMapCreated: (GoogleMapController controller) 
          _controller.complete(controller);
        ,
        markers: Set<Marker>.of(markers.values),
        onLongPress: (LatLng latLng) 
          // creating a new MARKER

          final MarkerId markerId = MarkerId('4544');
          final Marker marker = Marker(
            markerId: markerId,
            position: latLng,
          );

          setState(() 
            markers.clear();
            // adding a new marker to map
            markers[markerId] = marker;
          );
        ,
      ),
    );
  

  Widget _searchbar() 
    return Positioned(
      top: 50.0,
      right: 15.0,
      left: 15.0,
      child: Container(
        height: 50.0,
        width: double.infinity,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10.0), color: Colors.white),
        child: TextField(
          decoration: InputDecoration(
            hintText: 'Enter Address',
            border: InputBorder.none,
            contentPadding: EdgeInsets.only(left: 15.0, top: 15.0),
            suffixIcon: IconButton(
              icon: Icon(Icons.search),
              //onPressed: searchandNavigate,
              onPressed: () ,
              iconSize: 30.0,
            ),
          ),
          onChanged: (val) 
            setState(() 
              // searchAddr = val;
            );
          ,
        ),
      ),
    );
  

【问题讨论】:

每次触发 onLongPress 侦听器时,您都会清除标记列表。这就是为什么你总是只会看到一个 - 最后一个 - 设置标记。尝试向列表中添加新标记 好的,我已经删除了该 marker.clear()。现在你能帮我做什么吗 您每次都在创建具有相同标记 ID 的标记,即 4544 ,这就是为什么每次在 setState 上绘制屏幕时都会替换相同的标记 好的@AnirudhBagri 你能帮我解决这个问题吗,因为我已经尝试过但没有成功。你的帮助可以让我开心:) 【参考方案1】:

让我们从创建一个创建新标记并将其添加到标记映射的辅助函数开始。

 onLongPress: (LatLng latLng) 
          // creating a new MARKER

          var markerIdVal = markers.length + 1;
          String mar = markerIdVal.toString();
          final MarkerId markerId = MarkerId(mar);
          final Marker marker = Marker(markerId: markerId, position: latLng);

          setState(() 
            markers[markerId] = marker;
          );
        ,

【讨论】:

这个方法里面会包含什么 MyWayToGenerateId() 请帮助我,因为我对 Flutter 有点陌生 我是否需要在设置状态下添加返回标记.length + 1 ??? 编辑了我的答案并删除了创建新id的方法。这应该会有所帮助。 嘿兄弟,我稍微编辑了你的答案,它工作正常 :) 非常感谢你的帮助 :) 如果您觉得这个问题有用,请点赞。因为堆栈溢出时没有类似这样的问题【参考方案2】:

只需检查下面的代码。

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_google_map/appconstant.dart';
import 'dart:async';

import 'package:google_maps_flutter/google_maps_flutter.dart';

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

class MyApp extends StatefulWidget 
  @override
  _MyAppState createState() => _MyAppState();
  

class _MyAppState extends State<MyApp> 

  Completer<GoogleMapController> _controller = Completer();

  Iterable markers = [];

  Iterable _markers = Iterable.generate(AppConstant.list.length, (index) 
    return Marker(
      markerId: MarkerId(AppConstant.list[index]['id']),
      position: LatLng(
        AppConstant.list[index]['lat'],
        AppConstant.list[index]['lon'],
      ),
      infoWindow: InfoWindow(title: AppConstant.list[index]["title"])
    );
  );



  @override
  void initState() 
    setState(() 
      markers = _markers;
    );
    super.initState();
  

  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Maps Sample App'),
          backgroundColor: Colors.green[700],
        ),
        body: GoogleMap(
          mapType: MapType.normal,
          initialCameraPosition: CameraPosition(target: LatLng(23.7985053,                          
          90.3842538), zoom: 13),
          onMapCreated: (GoogleMapController controller) 
            _controller.complete(controller);
          ,
          markers: Set.from(markers),
        ),
      ),
    );
  

列表数据的另一个类

appconstant.dart

class AppConstant 
  static List<Map<String, dynamic>> list = [
    "title": "one", "id": "1", "lat": 23.7985053, "lon": 90.3842538,
    "title": "two", "id": "2", "lat": 23.802236, "lon": 90.3700,
    "title": "three", "id": "3", "lat": 23.8061939, "lon": 90.3771193,
  ];

【讨论】:

【参考方案3】:

只需创建一个每次创建新标记时都会计数的变量,并将此变量用作您的 markerId:

onLongPress: (LatLng latLng) 
  // creating a new MARKER


  final MarkerId markerId = MarkerId("$myId");
  final Marker marker = Marker(
    markerId: markerId,
    position: latLng,
  );

  setState(() 
    myId++;

    // adding a new marker to map
    markers[markerId] = marker;
  );
,

【讨论】:

我在使用 marker.add(marker) 时出现错误,它在 add 方法中显示错误 The method 'add' isn't defined for the class 'Map'. Try correcting the name to the name of an existing method, or defining a method named 'add' 尝试使用标记[markerId] = marker.地图没有添加方法 这应该可以。这与您接受的答案完全相同。我只使用一个显然必须启动的计数器变量 不,它不起作用。但非常感谢你的帮助:)

以上是关于用户如何在谷歌地图颤振上添加多个标记的主要内容,如果未能解决你的问题,请参考以下文章

如何在颤振中使用 json API 在谷歌地图中添加标记?

如何在谷歌地图上添加多个标记

如何在谷歌地图android上设置多个标记?

我们如何在谷歌地图中添加带有点击事件的多个标记? [复制]

按钮单击dialogFragment后如何在谷歌地图上添加标记?

怎么在谷歌地图上做标记呀