Search code examples
fluttergoogle-mapsgoogle-places-apifluttermap

moving the map with search location


I am recently integating the Google maps and places api and all is working but i am getting this problem that when i searches the place and suggestions come along with them but when i selects any of the suggestion then that location is not coming in the centre and also the text address is not changing according to selected location from the search

final TextEditingController _controller = TextEditingController();
  var uuid = const Uuid();
  String _sessionToken = '1234567890';
  List<dynamic> _placeList = [];

  _onChanged() {
    if (_controller.text.isNotEmpty) {
      if (_sessionToken == '' || _sessionToken.isEmpty) {
        setState(() {
          _sessionToken = uuid.v4();
        });
      }
      getSuggestion(_controller.text);
    } else {
      setState(() {
        _placeList.clear();
      });
    }
  }


  // Fetch place suggestions
  void getSuggestion(String input) async {
    const String PLACES_API_KEY = "";
    String baseURL = 'https://maps.googleapis.com/maps/api/place/autocomplete/json';
    String request = '$baseURL?input=$input&key=$PLACES_API_KEY&sessiontoken=$_sessionToken';

    var response = await http.get(Uri.parse(request));
    if (response.statusCode == 200) {
      var data = json.decode(response.body);
      setState(() {
        _placeList = data['predictions'];
      });
    } else {
      throw Exception('Failed to load predictions');
    }
  }

  // Fetch place details based on the selected place ID
  Future<void> getPlaceDetails(String placeId) async {
    const String PLACES_API_KEY = "AIzaSyAGEtunBXnzTCQkBaUJI4mzBQpw3X_C_6c";
    String request = 'https://maps.googleapis.com/maps/api/place/details/json?place_id=$placeId&key=$PLACES_API_KEY';

    var response = await http.get(Uri.parse(request));
    if (response.statusCode == 200) {
      var data = json.decode(response.body);
      double lat = data['result']['geometry']['location']['lat'];
      double lng = data['result']['geometry']['location']['lng'];

      LatLng selectedPosition = LatLng(lat, lng);
      _getAddressFromLatLng(selectedPosition);
      mapController.animateCamera(CameraUpdate.newLatLngZoom(selectedPosition, 15));

    } else {
      throw Exception('Failed to fetch place details');
    }
  }


  

  bool showAddressDetails = false;
  String dynamicAddress = "Move the pin to your location"; 
  LatLng currentPinPosition = const LatLng(26.9124, 75.7873); 

  late TextEditingController flatHouseController;
  late TextEditingController landmarkController;
  late GoogleMapController mapController;
    late TextEditingController yourNameController;
  late TextEditingController phoneNumberController;
  late TextEditingController alternatePhoneNumberController;
  late TextEditingController notesController;
   final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  // final FocusNode _mobileNumberFocusNode = FocusNode();

   String _selectedAddressType = "Home";

  @override
  @override
  void initState() {
    super.initState();
    flatHouseController = TextEditingController();
    landmarkController = TextEditingController();
    yourNameController = TextEditingController();
    phoneNumberController = TextEditingController();
    alternatePhoneNumberController = TextEditingController();
    notesController = TextEditingController();
    _getAddressFromLatLng(currentPinPosition);
       _controller.addListener(() {
      _onChanged();
    });
  }

  Future<void> _getAddressFromLatLng(LatLng position) async {
    try {
      List<Placemark> placemarks = await placemarkFromCoordinates(position.latitude, position.longitude);
      Placemark place = placemarks[0];
      setState(() {
        dynamicAddress = "${place.name}, ${place.locality}, ${place.administrativeArea}, ${place.country}";
        flatHouseController.text = place.name ?? '';
        landmarkController.text = place.subLocality ?? '';
      });
    } catch (e) {
      setState(() {
        dynamicAddress = "Address not found";
      });
    }
  }

  Future<void> _getCurrentLocation() async {
    bool serviceEnabled;
    LocationPermission permission;
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("Location services are disabled.")));
      return;
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("Location permission denied.")));
        return;
      }
    }

    if (permission == LocationPermission.deniedForever) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("Location permission is permanently denied.")));
      return;
    }
    Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    LatLng userLocation = LatLng(position.latitude, position.longitude);
    mapController.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(target: userLocation, zoom: 15)));
    setState(() {
      currentPinPosition = userLocation;
    });
    _getAddressFromLatLng(userLocation);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: AppColors.appbarColor,
        title: const Text("Confirm delivery location"),
      ),
      body: GestureDetector(
         onTap: () {
          FocusScope.of(context).unfocus();
        },
        child: Stack(
          
          children: [
            GoogleMap(
              initialCameraPosition: CameraPosition(
                target: currentPinPosition,
                zoom: 15,
              ),
              onMapCreated: (GoogleMapController controller) {
                mapController = controller;
              },
              onCameraMove: (CameraPosition position) {
                setState(() {
                  currentPinPosition = position.target; 
                });
              },
              onCameraIdle: () {
                _getAddressFromLatLng(currentPinPosition);
              },
            ),
            const Center(
              child: Icon(Icons.location_pin, size: 50, color: Colors.red),
            ),
           Positioned(
  top: 20,
  left: 16,
  right: 16,
  child: Column(
    children: <Widget>[
      TextField(
        controller: _controller,
        decoration: InputDecoration(
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(10),
          ),
          hintText: "Search your location here",
          hintStyle: TextStyle(color: Colors.grey.shade400, fontSize: 14),
          prefixIcon: const Icon(Icons.search_outlined, color: AppColors.appbarColor),
          suffixIcon: IconButton(
            icon: const Icon(Icons.cancel),
            onPressed: () {
              _controller.clear();
              setState(() {
                _placeList.clear();
              });
            },
          ),
        ),
      ),
      const SizedBox(height: 10),
      if (_placeList.isNotEmpty)
        Container(
          decoration: BoxDecoration(
            color: Colors.white, 
            borderRadius: BorderRadius.circular(10), 
          ),
          child: ListView.builder(
            shrinkWrap: true,
            itemCount: _placeList.length,
            itemBuilder: (context, index) {
              return Column(
                children: [
                  ListTile(
                    leading: Icon(Icons.location_on_outlined, color: AppColors.appbarColor),
                    title: Text(
                      _placeList[index]["description"],
                      style: TextStyle(color: Colors.black),
                    ),
                    onTap: () {
                      setState(() {
                        _controller.text = _placeList[index]["description"];
                        _placeList.clear();
                      });
                    },
                  ),
                  Divider(),
                ],
              );
            },
          ),
        ),
    ],
  ),
)

Solution

  • I solved that problem that i was not using the getPlacesDetails correctly and after called this function it worked for me