I'm pretty new (2 days in) to dart(flutter) so bare with me. I am trying to add markers to my OpenStreetMap map in my flutter app. I have a csv file with all the points I want to add that looks like this:
place_name | latitude | longitude |
---|---|---|
data | data | data |
I have figured out how to add a single marker - how can I loop through the rows in the csv file to add multiple markers? Here's my current add marker code.
Future<void> _addSingleMarker() async {
// Given latitude and longitude
final latitude = 53.7827922;
final longitude = -1.5547318;
markers.clear();
markers.add(GeoPoint(latitude: latitude, longitude: longitude));
await _addMarkersToMap();
}
Future<void> _addMarkersToMap() async {
for (GeoPoint marker in markers) {
print("Adding marker at latitude: ${marker.latitude}, longitude: ${marker.longitude}");
await mapController.addMarker(marker,
markerIcon: const MarkerIcon(
icon: Icon(
Icons.location_pin,
color: Colors.blue,
size: 48,
),
));
}
print("Markers added to the map");
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Map with Multiple Markers'),
),
body: MapWithMarkers(),
),
);
}
}
class MapWithMarkers extends StatelessWidget {
final List<LatLng> markerCoordinates = [
LatLng(53.7827922, -1.5547318),
LatLng(53.780416, -1.58270),
];
@override
Widget build(BuildContext context) {
return FlutterMap(
options: MapOptions(
center: LatLng(53.7827922, -1.5547318), // Initial map center
zoom: 12.0, // Initial zoom level
),
layers: [
TileLayerOptions(
urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
subdomains: ['a', 'b', 'c'],
),
MarkerLayerOptions(
markers: _buildMarkers(),
),
],
);
}
List<Marker> _buildMarkers() {
List<Marker> markers = [];
for (int i = 0; i < markerCoordinates.length; i++) {
markers.add(
Marker(
width: 80.0,
height: 80.0,
point: markerCoordinates[i],
builder: (ctx) => Icon(
Icons.location_pin,
color: Colors.blue,
size: 48,
),
),
);
}
return markers;
}
}