0

I am trying to display on the map view more than one custom icon, trying to taking care of the icons sizes (iOS case). The code I wrote seems to work fine with the first custom icon (I have 3), but when I add the code to add to the list of markers the other two custom icons, the map no longer shows any custom icons. This is my code:

class mapPage extends StatefulWidget {
  static const String routeName = '/mapPage';

  @override
  _mapPage createState() => _mapPage();
}

class _mapPage extends State<mapPage> {
  LatLng _initialcameraposition = LatLng(40.679425, 14.755968);
  GoogleMapController _mapController;
  String _mapStyle;
  List<Marker> _markers = <Marker>[];

  final Set<Marker> listMarkers = {};

  @override
  void initState() {
    super.initState();
    setCustomMarkers();
    rootBundle.loadString('assets/mapStyle.txt').then((string) {
      _mapStyle = string;
    });
  }

  _onMapCreated(GoogleMapController controller) {
    if (mounted)
      setState(() {
        _mapController = controller;
        _mapController.setMapStyle(_mapStyle);
      });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text(AppLocalizations.of(context).translate('explore')),
      ),
      drawer: navigationDrawer(),
      body: Container(
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
        child: new FutureBuilder(
            future: DefaultAssetBundle.of(context)
                .loadString('assets/turisticpoint.json'),
            builder: (context, snapshot) {
              var string = snapshot.data.toString();
              List<CustomAdapter> turisticPointList = parseJosn(string);

              if (turisticPointList.isNotEmpty) {
                for (int i = 0; i < turisticPointList.length; i++) {
                  _markers.add(Marker(
                      markerId: MarkerId('SomeId'),
                      position: LatLng(
                          double.parse(turisticPointList[i].latitudine),
                          double.parse(turisticPointList[i].longitudine)),
                      infoWindow: InfoWindow(
                        title: AppLocalizations.of(context)
                            .translate(turisticPointList[i].titolo),
                      )));
                }


              }

              return turisticPointList.isNotEmpty
                  ? new GoogleMap(
                      initialCameraPosition: CameraPosition(
                          target: _initialcameraposition, zoom: 15),
                      mapType: MapType.normal,
                      markers: Set<Marker>.of(_markers),
                      onMapCreated: _onMapCreated,
                      myLocationEnabled: true,
                    )
                  : new Center(child: new CircularProgressIndicator());
            }),
      ),
    );
  }

  Future<Uint8List> getBytesFromAsset(String path, int width) async {
    ByteData data = await rootBundle.load(path);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(),
        targetWidth: width);
    ui.FrameInfo fi = await codec.getNextFrame();
    return (await fi.image.toByteData(format: ui.ImageByteFormat.png))
        .buffer
        .asUint8List();
  }

  void setCustomMarkers() async {
    BitmapDescriptor portIcon, busIcon, trainIcon;

    final Uint8List markerIconPort = await getBytesFromAsset('assets/images/port.png', 100);
    //final Uint8List markerIconTrain = await getBytesFromAsset('assets/images/train.png', 100);
    //final Uint8List markerIconBus = await getBytesFromAsset('assets/images/train.png', 100);


    portIcon = BitmapDescriptor.fromBytes(markerIconPort);
    //trainIcon = BitmapDescriptor.fromBytes(markerIconTrain);
    //busIcon = BitmapDescriptor.fromBytes(markerIconTrain);

    //port
    _markers.add(Marker(
      markerId: MarkerId('SomeId'),
      position: LatLng(40.672842, 14.769194),
      infoWindow: InfoWindow(title: "Port 1"),
      icon: portIcon,
    ));

    _markers.add(Marker(
      markerId: MarkerId('SomeId'),
      position: LatLng(40.674126, 14.752421),
      infoWindow: InfoWindow(title: "Port 2"),
      icon: portIcon,
    ));

    //train
    _markers.add(Marker(
      markerId: MarkerId('SomeId'),
      position: LatLng(40.675804, 14.772802),
      infoWindow: InfoWindow(title: "Train"),
      icon: trainIcon,
    ));

    //bus
     _markers.add(Marker(
      markerId: MarkerId('SomeId'),
      position: LatLng(40.674102, 14.776989),
      infoWindow: InfoWindow(
        title: "Bus",
      ),
      icon: busIcon,
    ));
  }

  Future<String> loadAsset(BuildContext context) async {
    return await DefaultAssetBundle.of(context)
        .loadString('assets/turisticpoint.json');
  }

  List<CustomAdapter> parseJosn(String response) {
    if (response == null) {
      return [];
    }
    var decode = json.decode(response.toString());
    if (decode == null) {
      return [];
    }

    final parsed = decode.cast<Map<String, dynamic>>();
    return parsed
        .map<CustomAdapter>((json) => new CustomAdapter.fromJson(json))
        .toList();
  }
}

How can I fix my problem?

I hope you can forgive me if I have made some strange or stupid mistakes in the code, I am really new to the Flutter World.

TheOldBlackbeard
  • 395
  • 4
  • 22

1 Answers1

0

To load custom markers properly, you need to use BitmapDescriptor as shown below:

Note: I used random icons, but you can just use your custom icons by changing the path file in the BitmapDescriptor.

void setCustomMarkers() async {
  var portIcon, busIcon, trainIcon;

  portIcon = await BitmapDescriptor.fromAssetImage(
    ImageConfiguration(), "images/cool.png");
  busIcon = await BitmapDescriptor.fromAssetImage(
    ImageConfiguration(), "images/monkey.png");
  trainIcon = await BitmapDescriptor.fromAssetImage(
    ImageConfiguration(), "images/smile.png");

  //port
  _markers.add(Marker(
    markerId: MarkerId('1'),
    position: LatLng(40.672842, 14.769194),
    infoWindow: InfoWindow(title: "Port 1"),
    icon: portIcon,
  ));

_markers.add(Marker(
  markerId: MarkerId('2'),
  position: LatLng(40.674126, 14.752421),
  infoWindow: InfoWindow(title: "Port 2"),
  icon: portIcon,
));

//train
_markers.add(Marker(
  markerId: MarkerId('3'),
  position: LatLng(40.675804, 14.772802),
  infoWindow: InfoWindow(title: "Train"),
  icon: trainIcon,
));

//bus
_markers.add(Marker(
  markerId: MarkerId('4'),
  position: LatLng(40.674102, 14.776989),
  infoWindow: InfoWindow(title: "Bus"),
  icon: busIcon,
));

}
jabamataro
  • 1,154
  • 7
  • 13