user12420312
user12420312

Reputation:

Flutter Google Maps Markers from JSON file

I'm trying to add marker to my map widget based on the string in a Json file. When I run my code the map does not render. I think I am not accessing the list correctly. The markers: attribute in the Flutter_Google_maps widget now takes a Set().

I have seen other responses to questions "to add markers, first you should create an empty Set of type Marker and assign it to the markers: attribute in the google maps widget. Consequently, you append the desired Marker() to the created set using the add() method. Finally, you use setState() to rebuild the widget and display the updated Markers set on the UI." but it does not help

Here is my code so far :

JSON:

[
  {
    "name": "H1: Hatfield-Brooklyn",
    "colour": "FF8F8F",
    "coords": [
      {
        "ID": "385",
   "longitude": "28.044276",
    "latitude": "-26.145868"
      },
]

MAP:

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:gtbuddy/src/models/routes.dart';
import 'package:gtbuddy/src/ui/components/serviceArea.dart';



class MapSample extends StatefulWidget {

  final String selectedStation;


  MapSample({this.selectedStation});


@override
State<MapSample> createState() => MapSampleState();
}

class MapSampleState extends State<MapSample> {
  Future _future;

  Future<String> loadString() async =>
//      await rootBundle.loadString('assets/Routes/coords_${widget.selectedStation}.json');
  await rootBundle.loadString('assets/route/coords_${widget.selectedStation}.json');
  List<Marker> allMarkers = [];
  GoogleMapController _controller;




  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _future = loadString();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Bus Routes"),
        centerTitle: true,
        backgroundColor: Color.fromRGBO(59, 62, 64, 1),
        actions: <Widget>[
          FlatButton(
            textColor: Colors.white,
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => busStationList()),
              );
            },
            child: Icon(Icons.add),
          ),
        ],
      ),
      body: Stack(children: [
        Container(
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          child: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot snapshot) {
              if (!snapshot.hasData) {
                return CircularProgressIndicator();
              }


              List<Routes> parsedJson = jsonDecode(snapshot.data);


              allMarkers = parsedJson.map((element) {

                element.coords.forEach((internalItem){
                  return Marker(
                    //here you need to create a random name.

                      markerId: MarkerId(internalItem.iD),
                      position: LatLng(internalItem.latitude, internalItem.longitude));
                });


              }).toList();

              return GoogleMap(
                initialCameraPosition: CameraPosition(
                    target: LatLng(-26.0000, 28.0000), zoom: 10.151926040649414),
                markers: Set.from(allMarkers),
                onMapCreated: mapCreated,
              );
            },
          ),
        ),
      ]),
    );
  }
  void mapCreated(controller) {
    setState(() {
      _controller = controller;
    });
  }
}

Upvotes: 0

Views: 2662

Answers (1)

ahmetakil
ahmetakil

Reputation: 908

Maps except a set of markers not lists so use {} not [] use

Set<Marker> allMarkers = {};

Upvotes: 0

Related Questions