Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

dart - Flutter how to add 2 markers in same map

I have data in which I have lat and long values of starting and endpoint.

I am trying to show marker like this

class _TripRouteScreenState extends State<TripRouteScreen> {
  BitmapDescriptor pinLocationIcon;

  var start_currentPostion;
  var end_currentPostion;
  Map<MarkerId, Marker> markers =
      <MarkerId, Marker>{}; // CLASS MEMBER, MAP OF MARKS

  void setCustomMapPin() async {
    pinLocationIcon = await BitmapDescriptor.fromAssetImage(
        ImageConfiguration(devicePixelRatio: 2.5), 'images/pin.png');
  }

  @override
  void initState() {
    super.initState();
    setCustomMapPin();
    working();

  }

  working(){
    print(widget.data);

    double start_latitude = widget.data['start']['lat'].toDouble();
    double start_longitude = widget.data['start']['lon'].toDouble();

    double end_latitude = widget.data['end']['lat'].toDouble();
    double end_longitude = widget.data['end']['lon'].toDouble();

    start_currentPostion = LatLng(start_latitude, start_longitude); //this is the marker 1 location  which is already set and showing in map
    end_currentPostion = LatLng(end_latitude, end_longitude); // this is the marker 2 location which needs to be set and show marker on this value 

    print(start_currentPostion);
    print(end_currentPostion);
    var snip = widget.data["start"]["address"];
    final Map<String, Marker> _markers = {};

    setState(() {
      final MarkerId markerId = MarkerId('1');

      // creating a new MARKER
      final Marker marker = Marker(
        markerId: markerId,
        icon: pinLocationIcon,
        position: start_currentPostion,
        infoWindow: InfoWindow(title: 'Address',snippet: snip),
      );

      setState(() {
        // adding a new marker to map
        markers[markerId] = marker;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          leading: GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: Icon(Icons.arrow_back)),
          centerTitle: true,
          flexibleSpace: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('images/nav.jpg'),
                fit: BoxFit.cover,
              ),
            ),
          ),
          backgroundColor: Colors.transparent,
          title: Text(
            'Route Location',
            style: TextStyle(fontFamily: 'UbuntuBold'),
          ),
          actions: [
            Padding(
              padding: const EdgeInsets.only(right: 15),
              child: Icon(
                Icons.notifications_none,
                size: 33,
              ),
            )
          ]),
      body: GoogleMap(
        mapType: MapType.normal,
        initialCameraPosition: CameraPosition(
          target: start_currentPostion,
          zoom: 15,
        ),
        markers: Set<Marker>.of(markers.values), // YOUR MARKS IN MAP
      ),
    );
  }
}

The issue is I am able to add a marker on the map but on only starting point :D Mean start_currentPostion I need to add a marker on the end point also which is end_currentPostion But I am stuck by how can I do this. From tutorials and other answers finally, I am able to add 1 marker but don't know how to add a second marker now.

question from:https://stackoverflow.com/questions/65920111/flutter-how-to-add-2-markers-in-same-map

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

enter image description here

So I tried with your code and I added some changes into your code now this is running. So first, I created an empty list for storing your Markers data. After that created 2 marker id and added that id into a list and then created 2 markers with different locations wrt markers id and added this marker to setmarkers and then simply access the value of this into a google map. for drawing the route on google map you can check the medium article and this Github post

class _TripRouteScreenState extends State<HomeScreen> {
  BitmapDescriptor pinLocationIcon;

  var start_currentPostion;
  var end_currentPostion;

  Map<MarkerId, Marker> setmarkers = {};
  List listMarkerIds = List();  // For store data of your markers 

  @override
  void initState() {
    super.initState();
    working();
  }

  working() {

    // You just need to pass dynamically your data

    double start_latitude = 19.965651;
    double start_longitude = 73.771683;

    double end_latitude = 19.997454;
    double end_longitude = 73.789803;

    start_currentPostion = LatLng(start_latitude, start_longitude);
    end_currentPostion = LatLng(end_latitude, end_longitude);


    setState(() {
      MarkerId markerId1 = MarkerId("1");
      MarkerId markerId2 = MarkerId("2");

      listMarkerIds.add(markerId1);
      listMarkerIds.add(markerId2);

      Marker marker1 = Marker(
        markerId: markerId1,
        position: LatLng(start_latitude, start_longitude),
        icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRed),
      );

      Marker marker2 = Marker(
        markerId: markerId2,
        position: LatLng(end_latitude, end_longitude),
        icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRed),  // you can change the color of marker
      );

      setmarkers[markerId1] = marker1;  // I Just added here markers on the basis of marker id 
      setmarkers[markerId2] = marker2;

    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          leading: GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: Icon(Icons.arrow_back)),
          centerTitle: true,
          flexibleSpace: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('images/nav.jpg'),
                fit: BoxFit.cover,
              ),
            ),
          ),
          backgroundColor: Colors.transparent,
          title: Text(
            'Route Location',
            style: TextStyle(fontFamily: 'UbuntuBold'),
          ),
          actions: [
            Padding(
              padding: const EdgeInsets.only(right: 15),
              child: Icon(
                Icons.notifications_none,
                size: 33,
              ),
            )
          ]),
      body: GoogleMap(
        mapType: MapType.normal,
        initialCameraPosition: CameraPosition(
          target: start_currentPostion,
          zoom: 15,
        ),
        markers: Set.of(setmarkers.values), // YOUR MARKS IN MAP
      ),
    );
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...