Flutter Google Map работает на версии Android, но не на версии iPhone.IOS

Программируем под IOS
Ответить
Anonymous
 Flutter Google Map работает на версии Android, но не на версии iPhone.

Сообщение Anonymous »

Я использую язык программирования приложений Flutter
Я создал страницу, содержащую Карты Google, с помощью которой пользователь указывает свое местоположение, чтобы сохранить адрес и данные о местоположении в своей учетной записи при создании учетной записи< /p>
При запуске версии на Android работает хорошо
Но при запуске версии на iPhone карта не отображается
Я предоставил все необходимые разрешения
И я изменил файл AppDelegate.swift и добавил в него ключ API
Однако , не сработало
Xcode версии 16
IOS 18
dart 3.5.4
Флаттер 3.22
`

class MapScreen extends StatefulWidget {
const MapScreen({super.key});
@override
State createState() => OrderTrackingPageState();
}

class OrderTrackingPageState extends State {
double? latitude;
double? longitude;
final Completer _controller = Completer();

LocationData? currentLocation;
bool _isLoading = true;

@override
void initState() {
super.initState();
getCurrentLocation();

if (currentLocation != null) {
setState(() {
_isLoading = false;
sourceLocation =
LatLng(currentLocation!.latitude!, currentLocation!.longitude!);
latitude = currentLocation!.latitude;
longitude = currentLocation!.longitude;
});
}
}

LatLng? sourceLocation;
String _selectedAddress = '';
String City = '';
String Country = '';
String Postalcode = '';
String State = '';
String Address = '';

void _handleMapLongPress(LatLng position) async {
String apiKey = 'AIz***********************************';
String url =
'https://maps.googleapis.com/maps/api/ge ... ey=$apiKey';

http.Response response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
Map data = jsonDecode(response.body);
if (data['status'] == 'OK') {
String formattedAddress = data['results'][0]['formatted_address'];
List addressParts = formattedAddress.split(', ');
String country = addressParts.last;
String city = addressParts[addressParts.length - 2];
String street =
addressParts.sublist(0, addressParts.length - 2).join(', ');

setState(() {
Address = street;
City = city;
Country = country;
});

List addressComponents =
data['results'][0]['address_components'];
String postalCode = '';
String state = '';

for (var component in addressComponents) {
List types = component['types'];
if (types.contains('postal_code')) {
postalCode = component['long_name'];
setState(() {
Postalcode = postalCode;
});
} else if (types.contains('administrative_area_level_1')) {
state = component['long_name'];
setState(() {
State = state;
});
}
}

setState(() {
_selectedAddress = '''
$country, $city,
$street
Postal Code: $postalCode
State: $state
''';
});
}
}
}

void _showAddressPopup() {
showDialog(
context: context,
builder: (context) {
TextEditingController addressController = TextEditingController();
return AlertDialog(
title: const Text('Add Address'),
content: TextField(
controller: addressController,
decoration: InputDecoration(
hintText: _selectedAddress,
),
),
actions: [
TextButton(
onPressed: () {
String address = addressController.text;
Navigator.of(context).pop();
},
child: const Text('Save'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('Cancel'),
),
],
);
},
);
}

Future getCurrentLocation() async {
Location location = Location();
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;
}
}

currentLocation = await location.getLocation();
setState(() {
_isLoading = false;
});
setState(() {
_isLoading = false;
sourceLocation =
LatLng(currentLocation!.latitude!, currentLocation!.longitude!);
});

String apiKey = 'AIz***********************************';
String url =
'https://maps.googleapis.com/maps/api/ge ... ey=$apiKey';

http.Response response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
Map data = jsonDecode(response.body);
if (data['status'] == 'OK') {
String formattedAddress = data['results'][0]['formatted_address'];
List addressParts = formattedAddress.split(', ');
String country = addressParts.last;
String city = addressParts[addressParts.length - 2];
String street =
addressParts.sublist(0, addressParts.length - 2).join(', ');

setState(() {
Address = street;
City = city;
Country = country;
});

List addressComponents =
data['results'][0]['address_components'];
String postalCode = '';
String state = '';

for (var component in addressComponents) {
List types = component['types'];
if (types.contains('postal_code')) {
postalCode = component['long_name'];
setState(() {
Postalcode = postalCode;
});
} else if (types.contains('administrative_area_level_1')) {
state = component['long_name'];
setState(() {
State = state;
});
}
}

setState(() {
_selectedAddress = '''
$country, $city,
$street
Postal Code: $postalCode
State: $state
''';
});
}
}
}

Future animateToCurrentLocation() async {
if (currentLocation != null) {
final GoogleMapController controller = await _controller.future;
controller.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
target: LatLng(
currentLocation!.latitude!,
currentLocation!.longitude!,
),
zoom: 10.0,
),
),
);
}
}

List polylineCoordinates = [];

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: MYTHEME.APPBAR_COLOR,
title: const Text('تحديد الموقع الحالي'),
),
body: _isLoading
? const Center(child: CircularProgressIndicator())
: Column(
children: [
Container(
color: MYTHEME.APPBAR_COLOR,
padding: const EdgeInsets.all(16.0),
child: const Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
'1. تحديد العنوان',
style: TextStyle(
fontWeight: FontWeight.bold,
color: MYTHEME.MAIN_COLOR),
),
Spacer(),
Text(
'في التقدم',
style: TextStyle(
fontWeight: FontWeight.bold,
color: MYTHEME.MAIN_COLOR),
),
],
),
SizedBox(height: 8.0),
Row(
children: [
Text(
'2. إدخال البيانات',
style: TextStyle(
fontWeight: FontWeight.bold, color: Colors.red),
),
Spacer(),
Text(
'في التقدم',
style: TextStyle(
fontWeight: FontWeight.bold, color: Colors.red),
),
],
),
],
),
),
Expanded(
child: GoogleMap(
onLongPress: _handleMapLongPress,
initialCameraPosition: CameraPosition(
target:
sourceLocation ?? const LatLng(24.774265, 46.738586),
zoom: 13.5,
),
markers: {
Marker(
markerId: const MarkerId("currentLocation"),
position: LatLng(currentLocation!.latitude!,
currentLocation!.longitude!),
infoWindow: const InfoWindow(
title: 'موقعك الحالي',
),
),
},
onMapCreated: (mapController) {
_controller.complete(mapController);
},
polylines: {
Polyline(
polylineId: const PolylineId("route"),
points: polylineCoordinates,
color: const Color(0xFF7B61FF),
width: 6,
),
},
),
),
if (_selectedAddress.isNotEmpty)
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(_selectedAddress),
),
SizedBox(
width: 180,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: MYTHEME.MAIN_COLOR),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CreateAccount(
city: City,
country: Country,
postalcode: Postalcode,
state: State,
address: Address,
)));
},
child: const Padding(
padding: EdgeInsets.only(right: 20, left: 20),
child: Row(
children: [
Icon(Icons.arrow_back_ios),
Text(
'التالي',
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 20),
)
],
),
)),
)
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
animateToCurrentLocation();
},
child: const Icon(Icons.maps_home_work_outlined),
),
);
}
}


Подробнее здесь: https://stackoverflow.com/questions/792 ... ne-version
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»