Home > Back-end >  Flutter google maps custom icon
Flutter google maps custom icon

Time:12-31

I can't seem to work out how to use custom icons in my app. Nothing I have tried so far have worked. Below is my relevant code. The problem I have is that the customIcon variable seems to be null and the default code is kicking in as you can see in addMarker code. Im using a Set to put my markers into. Im also creating a customIcon with async method and are running them in the initState method. Can you please take a look and provide me with some help would be much appriciated!

@override
  void initState() {
    //customIcon1 = setCustom();
    setCustomIcon();
    print('CustomIcon is: ${customIcon.toString()}');
    _addMarker();
    super.initState();
  }

  //TODO Custom Icon is null I have to get this to work somehow!
  setCustomIcon() async {
    customIcon = await BitmapDescriptor.fromAssetImage(
        ImageConfiguration(devicePixelRatio: 2.5),
        'images/image1.png');
  }

void _addMarker() {
    setState(() {
      _markers!.add(Marker(
          markerId: MarkerId('1'),
          //icon: customIcon!,
          icon: customIcon ??
              BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueYellow),
          position: LatLng(59.36492713861164, 18.063758410239704),
          //59.3293, 18.0686
          infoWindow: InfoWindow(
            title: 'title 1',
            snippet: 'test 1',
          )));
      _markers!.add(Marker(
          markerId: MarkerId('2'),
          //icon: customIcon!,
          icon:
              BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueYellow),
          position: LatLng(58.17027695163088, 13.618293330200967),
          //59.3293, 18.0686
          infoWindow: InfoWindow(
            title: 'title 2',
            snippet: 'test 2',
          )));
    });
  }


body: GoogleMap(
        myLocationButtonEnabled: false,
        zoomControlsEnabled: false,
        initialCameraPosition: _initialCameraPosition,
        onMapCreated: (controller) => _googleMapController = controller,
        markers: {
          //Iterate with get over all the markers in the Set instead of this!
          _markers!.elementAt(0), _markers!.elementAt(1),
          
        },

CodePudding user response:

Please refer to below code


class MapDemo extends StatelessWidget {
  const MapDemo({Key key}) : super(key: key);

 /*Controller*/
  GoogleMapController mapController;

  /*Variable declaration*/
  bool customFlag = false;
  BitmapDescriptor customIcon1;


 /*Custom Marker for Maps*/
  createMarker(context) {
    if (customIcon1 == null) {
      ImageConfiguration configuration = createLocalImageConfiguration(context);
      BitmapDescriptor.fromAssetImage(configuration, ImagePaths.dcGlobe) /* ImagePaths.dcGlobe is an asset image */
          .then((icon) {
        customIcon1 = icon;
      });
    }
  }

 

  @override
  Widget build(BuildContext context) {
    createMarker(context);
    return Scaffold(
      body: Column(
        children: [
          LocationMaps(
            mapController: mapController,
            customFlag: customFlag,
            customIcon1: customIcon1,
            longitudeValues: 85,
            latitudeValues: 12.0,
          ),
          
        ],
      ),
    );
  }
}

class LocationMaps extends StatelessWidget {
  GoogleMapController mapController;
  bool customFlag;
  final BitmapDescriptor customIcon1;
  final longitudeValues;
  final latitudeValues;

  LocationMaps({
    Key key,
    this.mapController,
    this.customFlag,
    this.customIcon1,
    this.longitudeValues,
    this.latitudeValues,
  }) : super(key: key);

  double locationLatitude = 0.0;
  double locationLongitude = 0.0;

  LatLng _center;
  List<Marker> _markers = <Marker>[];

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  Widget build(BuildContext context) {
    locationLatitude = double.parse(latitudeValues);
    locationLongitude = double.parse(longitudeValues);
    _center = LatLng(locationLatitude, locationLongitude);
    _markers.add(Marker(
        icon: customFlag == true ? customIcon1 : null,
        markerId: MarkerId(''),
        position: LatLng(locationLatitude, locationLongitude),
        infoWindow: InfoWindow(title: '')));
    return ClipRRect(
      borderRadius: BorderRadius.circular(8.0),
      child: Container(
        color: AppColors.creamColor,
        width: ScreenUtil().screenWidth,
        child: Column(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(8.0),
              child: Container(
                width: ScreenUtil().screenWidth,
                height: ScreenUtil().setHeight(120.0),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8.0),
                ),
                child: GoogleMap(
                  myLocationButtonEnabled: (Platform.isAndroid) ? true : false,
                  onMapCreated: _onMapCreated,
                  initialCameraPosition: CameraPosition(
                    target: _center,
                    zoom: 13.0,
                  ),
                  mapType: MapType.normal,
                  markers: Set<Marker>.of(_markers),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}



CodePudding user response:

Try these steps:

  • Get user location (if required)

  • Add Markers

  • Set custom Icon

    class MapHome extends StatefulWidget {
                   List<BarData> mapData = []; //Array List
                   Map visitData;
                   MapHome(this.mapData, this.visitData, {Key? 
                   key}) : super(key: key);
    
                   @override
                   _MapHomeState createState() => _MapHomeState();
                 }
    
                 class _MapHomeState extends State<MapHome> {
                 //MARK: - Variables & Constants
                   final _mapHomeScaffKey = 
                   GlobalKey<ScaffoldState>();
                   GoogleMapController? _controller;
                   Set<Marker> _markers = {};
                   BitmapDescriptor? customIcon;
                   bool isLoading = false;
                   final List<LatLng> nearbyCarsLocation = [];
                   LocationData? _currentPosition;
                   String? _address, _dateTime;
                   Location location = Location();
    
                 //MARK: - Arrays & Dictionaries
    
                 //MARK: -View LifeCycle
                   @override
                   void initState() {
                     super.initState();
                     setState(() {
                       isLoading = true;
                     });
                     getLoc(context);
                   }
    
                   @override
                   void dispose() {
                     _controller!.dispose();
                     super.dispose();
                   }
    
                   Future<void> _onMapCreated(GoogleMapController 
                   controller) async {
                 // ignore: prefer_conditional_assignment
                     if (_currentPosition == null) {
                       _currentPosition = await 
                      location.getLocation();
                     }
                     setState(() {
                       _controller = controller;
                       for (var mapDetails in widget.mapData) {
                         setState(() {
                           nearbyCarsLocation.add(LatLng(
                  double.parse(mapDetails.latitude.toString()),
               double.parse(mapDetails.longitude.toString())));
                         });
                       }
                     });
                     _addMarkers();
                   }
    
                   getLoc(BuildContext context) async {
                     bool _serviceEnabled;
                     PermissionStatus _permissionGranted;
                     _serviceEnabled = await location.serviceEnabled();
                     if (!_serviceEnabled) {
                       _serviceEnabled = await location.requestService();
                       if (!_serviceEnabled) {
                         return;
                       }
                     }
    
                     _permissionGranted = await location.hasPermission();
                     if (_permissionGranted == PermissionStatus.denied) {
                       _permissionGranted = await location.requestPermission();
                       if (_permissionGranted != PermissionStatus.granted) {
                         return;
                       }
                     }
    
                     _currentPosition = await location.getLocation();
                     DateTime now = DateTime.now();
                     var _dateTime = DateFormat('EEE d MMM kk:mm:ss ').format(now);
                     if (_currentPosition != null) {
                       setState(() {
                         isLoading = false;
                       });
                       _addMarkers();
                       _setCustomMarker();
                     } else {
                       setState(() {
                         isLoading = false;
                       });
                     }
                   }
    
                   @override
                   Widget build(BuildContext context) {
                     return SafeArea(
                         child: Scaffold(
                       appBar: AppBar(
                           toolbarHeight: 60.0,
                           titleSpacing: 0.5,
                           // automaticallyImplyLeading: true,
                           leading: GestureDetector(
                             onTap: () {
                               Navigator.pop(context);
                             },
                             child: Padding(
                               padding: const EdgeInsets.all(16.0),
                               child: Image.asset(
                                 Commons.assetPath   "icon_arrow_back.png",
                               ),
                             ),
                           ),
                           title: const Text(
                             'Map',
                             textAlign: TextAlign.left,
                             style: TextStyle(
                               color: Colors.white,
                               fontSize: 18.0,
                               fontFamily: Commons.fontFamily,
                               fontWeight: FontWeight.w700,
                             ),
                           ),
                           actions: <Widget>[
                             Padding(
                               padding: const EdgeInsets.fromLTRB(5.0, 5.0, 12.0, 5.0),
                               child: Row(
                                 mainAxisAlignment: MainAxisAlignment.end,
                                 crossAxisAlignment: CrossAxisAlignment.center,
                                 children: [
                                   GestureDetector(
                                     onTap: () {
                                     },
                                     child: Padding(
                                       padding: const EdgeInsets.fromLTRB(10.0, 5.0, 5.0, 5.0),
                                       child: Image.asset(
                                         Commons.assetPath   'icon_search.png',
                                         height: 20.0,
                                         width: 20.0,
                                       ),
                                     ),
                                   ),
                                 ],
                               ),
                             ),
                           ]),
                       key: _mapHomeScaffKey,
                       body: isLoading == true
                           ? SpinKitSpinningLines(
                               color: HexColor('#2a48ae'),
                               itemCount: 7,
                             )
                           : Stack(children: <Widget>[
                               GoogleMap(
                                 onMapCreated: _onMapCreated,
                                 initialCameraPosition: CameraPosition(
                                   target: LatLng(_currentPosition!.latitude!,
                                       _currentPosition!.longitude!),
                                   zoom: 12,
                                 ),
                                 buildingsEnabled: true,
                                 indoorViewEnabled: true,
                                 myLocationEnabled: true,
                                 myLocationButtonEnabled: true,
                                 mapType: MapType.normal,
                                 markers: _markers,
                               )
                             ]),
                     ));
                   }
    
                   //MARK: - Class Methods
                   void _setCustomMarker() async {
                     final Uint8List markerIcon =
                         await getBytesFromAsset(Commons.assetPath   'map_marker.png', 70);
                     customIcon = BitmapDescriptor.fromBytes(markerIcon);
                     // customIcon = await BitmapDescriptor.fromAssetImage(
                     //     const ImageConfiguration(size: Size(2.0, 2.0)), Commons.assetPath   'map_marker.png');
                   }
    
                   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 _addMarkers() {
                     setState(() {
                       debugPrint(nearbyCarsLocation.toString());
                       for (var i = 0; i < nearbyCarsLocation.length; i  ) {
                         var now = DateTime.now().millisecondsSinceEpoch;
                         _markers.add(Marker(
                             markerId:
                                 MarkerId(nearbyCarsLocation[i].toString()   now.toString()),
                             position: nearbyCarsLocation[i],
                             onTap: () {
                             },
                             icon: customIcon!
                             ));
                       }
                     });
                   }
                 }
    
  • Related