3

How can the user add multiple markers when user long press on the map. in this code, I've done single map. when user long press on the map it will automatically add one marker but I don't know how I can add multiple markers on the map. I tried lots of codes but I am not getting the proper result. hope you understand the question. your small help can make my day. Thanks in advance.

Here is the code I've tried :)

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;
            });
          },
        ),
      ),
    );
  }
}
Rutvik Gumasana
  • 1,458
  • 11
  • 42
  • 66
  • 1
    you are clearing your markers list every time the onLongPress listener is triggered. Thats why you will allways see only one - the last - set marker. Try adding new markers to the list – Lukas Nov 19 '19 at 05:51
  • Okay i've removed that marker.clear(). now can you help me what i have to do next – Rutvik Gumasana Nov 19 '19 at 06:09
  • You are creating marker with the same marker id everytime, i.e. *4544* , this is why the same marker gets replaced everytime the screen is painted on setState – Anirudh Bagri Nov 19 '19 at 06:16
  • Okay @AnirudhBagri can you please help me with that, because I've tried but not succeed. Your help can make my day :) – Rutvik Gumasana Nov 19 '19 at 06:18

3 Answers3

6

Let's start with creating a helper function that creates a new marker and adds it to the markers map.

 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;
          });
        },
Anirudh Bagri
  • 2,346
  • 1
  • 21
  • 33
5

enter image description here

just check below code .

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),
        ),
      ),
    );
  }
}

another class for list data

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},
  ];
}
Jewel Rana
  • 2,397
  • 1
  • 19
  • 28
1

just create a variable that counts up every time a new marker is created and use this var as your 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;
  });
},
Lukas
  • 490
  • 3
  • 15