How add marker with google_maps_flutter?

Issue

I am using google_maps_flutter, I would like to know how to add a marker when clicking somewhere on the map. I am new to flutter.

import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class SearchGaragesInMapScreenMap extends StatefulWidget {
  @override
  State<SearchGaragesInMapScreenMap> createState() =>
      SearchGaragesInMapScreenMapState();
}

class SearchGaragesInMapScreenMapState
    extends State<SearchGaragesInMapScreenMap> {
  final Completer<GoogleMapController> _controller = Completer();
  LatLng _myPosition = const LatLng(-12.0316827, -77.0492965);
  BitmapDescriptor _markerIcon = BitmapDescriptor.defaultMarker;

  @override
  void initState() {
    super.initState();
    _getMyPosition();
  }

  @override
  Widget build(BuildContext context) {
    return GoogleMap(
      mapType: MapType.normal,
      initialCameraPosition: CameraPosition(target: _myPosition, zoom: 15),
      onMapCreated: (GoogleMapController controller) {
        _controller.complete(controller);
      },
      markers: {
        _positionMarker(
          '1',
          _myPosition.latitude,
          _myPosition.longitude,
          /*AppMarkers.myMarker, 55, 35*/
        )
      },
      zoomControlsEnabled: false,
    );
  }

  Marker _positionMarker(String id, double latitude, double longitude,
      [String iconUrl, double iconWidth = 18, double iconHeight = 40]) {
    _setMarkerIcon(iconUrl, iconWidth, iconHeight);
    log('$_markerIcon');
    return Marker(
        markerId: MarkerId(id),
        position: LatLng(latitude, longitude),
        icon: _markerIcon);
  }

  void _getMyPosition() async {
    final Position _position = await _determinePosition();
    setState(() {
      _myPosition = LatLng(_position.latitude, _position.longitude);
    });
  }

  void _setMarkerIcon(
      [String iconUrl, double iconWidth, double iconHeight]) async {
    if (iconUrl != null) {
      final BitmapDescriptor _icon = await BitmapDescriptor.fromAssetImage(
          ImageConfiguration(size: Size(iconWidth, iconHeight)), iconUrl);
      setState(() {
        _markerIcon = _icon;
      });
    }
  }
}

Future<Position> _determinePosition() async {
  bool serviceEnabled;
  LocationPermission permission;
  serviceEnabled = await Geolocator
      .isLocationServiceEnabled(); // Verifica si este disp. tiene los servicios de ubicacion habilitados
  if (!serviceEnabled) {
    return Future.error('Location services are disabled.');
  }
  permission =
      await Geolocator.checkPermission(); // El usuario de permisos de ubicaciĆ³n
  if (permission == LocationPermission.deniedForever) {
    return Future.error(
        'Location permissions are permantly denied, we cannot request permissions.');
  }
  if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();
    if (permission != LocationPermission.whileInUse &&
        permission != LocationPermission.always) {
      return Future.error(
          'Location permissions are denied (actual value: $permission).');
    }
  }
  return await Geolocator.getCurrentPosition();
}

This is my code, this code I got from the pub.dev page. If it shows me the map on the device, so there is no problem in that case.

It’s my first time using maps in flutter, and I’m a bit lost.
If you have any documentation, tutorial or video it would be very helpful.

Solution

You can use the onTap callback.

 Set<Marker> markers = { _positionMarker(
          '1',
          _myPosition.latitude,
          _myPosition.longitude,
          /*AppMarkers.myMarker, 55, 35*/
        )};
       
  
Widget build(BuildContext context) {
    return GoogleMap(
      onTap: (position) => createCurrentMarker(position),
      mapType: MapType.normal,
      initialCameraPosition: CameraPosition(target: _myPosition, zoom: 15),
      onMapCreated: (GoogleMapController controller) {
        _controller.complete(controller);
      },
      markers: markers,
      zoomControlsEnabled: false,
    );
  }


//this is your add marker function
 void createCurrentMarker(LatLng position) async {
       setState(() {
          markers.add(Marker(markerId: MarkerId('new location'), position: position
          ));
    });
  }

Answered By – Huthaifa Muayyad

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *