Home > Enterprise >  How to assign a list of latitude and longitude to a list of type Marker in Flutter
How to assign a list of latitude and longitude to a list of type Marker in Flutter

Time:01-05

I have a list of type Map<String, dynamic> named positionMarkers which holds latitudes and longitudes along with their ID's that I would like to map accordingly into a list of type Marker i.e List<Marker>. I need the id in positionMarkers and the lat and lng to go into MarkerId() and LatLng() respectively. I'm pretty sure that this can be achieved by using loops but cannot seem to figure how. Any help would be appreciated:

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class MapMarkers with ChangeNotifier {
  List<Map<String, dynamic>> positionMarkers = [
    {
      'id': 1,
      'lat': 22.6434340,
      'lng': 88.446740,
    },
    {
      'id': 2,
      'lat': 22.6435442,
      'lng': 88.456742,
    },
    {
      'id': 3,
      'lat': 22.6436544,
      'lng': 88.466744,
    },
    {
      'id': 4,
      'lat': 22.6437646,
      'lng': 88.476746,
    },
    {'id': 5, 'lat': 22.6438748, 'lng': 88.486748}
  ];

  final List<Marker> markers = [
    Marker(
      markerId: MarkerId(),
      position: LatLng(),
      infoWindow: InfoWindow(),
    )
  ];
}

CodePudding user response:

Is this what you want?

final List<Marker> markers = [];

void _createMarkers() {
  for (int i = 0; i < positionMarkers.length; i  ) {
    markers.add(
      Marker(
        markerId: MarkerId(positionMarkers[i]['id']),
        position: LatLng(positionMarkers[i]['lat'], positionMarkers[i]['lng']),
        infoWindow: InfoWindow(
          title: 'Marker ${positionMarkers[i]['id']}',
        ),
      ),
    );
  }
}

CodePudding user response:

Try this,

    final List<Marker> markers = List.empty(growable: true);
    for (var i in positionMarkers) {
      // markerId is i["id]
      // lat is i["lat"]
      // lng is i["lng"]
      markers.add(
        Marker(
          markerId: MarkerId(i["id"]),
          position: LatLng(i["lat"], i["lng"]),
          infoWindow: InfoWindow(),
        ),
      );
    }
  • Related