我最近正在集成 Google 地图和地点 api,一切正常,但我遇到了这个问题,当我搜索该地点时,建议随之而来,但当我选择任何建议时,该位置不会出现在中心而且文本地址不会根据搜索中选择的位置而改变
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(),
],
);
},
),
),
],
),
)
我解决了我没有正确使用 getPlacesDetails 的问题,并且在调用此函数后它对我有用