最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ios - Flutter Google Map works on Android version but not on iPhone version - Stack Overflow

programmeradmin1浏览0评论

I use the flutter application programming language

I created a page containing Google Maps through which the user specifies his location to save the address and location data in his account when creating the account

When running the version on Android, it works well

But when running the version on iPhone, the map does not appear

I put all the required permissions

And I modified the AppDelegate.swift file and added the api key to the file

However, it did not work

Xcode version 16

IOS 18

dart 3.5.4

flutter 3.22

`

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

class OrderTrackingPageState extends State<MapScreen> {
  double? latitude;
  double? longitude;
  final Completer<GoogleMapController> _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 =
        '=${position.latitude},${position.longitude}&key=$apiKey';

    http.Response response = await http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      Map<String, dynamic> data = jsonDecode(response.body);
      if (data['status'] == 'OK') {
        String formattedAddress = data['results'][0]['formatted_address'];
        List<String> 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<dynamic> addressComponents =
            data['results'][0]['address_components'];
        String postalCode = '';
        String state = '';

        for (var component in addressComponents) {
          List<dynamic> 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<void> 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 =
        '=${currentLocation!.latitude},${currentLocation!.longitude}&key=$apiKey';

    http.Response response = await http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      Map<String, dynamic> data = jsonDecode(response.body);
      if (data['status'] == 'OK') {
        String formattedAddress = data['results'][0]['formatted_address'];
        List<String> 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<dynamic> addressComponents =
            data['results'][0]['address_components'];
        String postalCode = '';
        String state = '';

        for (var component in addressComponents) {
          List<dynamic> 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<void> 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<LatLng> 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) {
                      _controllerplete(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),
      ),
    );
  }
}
发布评论

评论列表(0)

  1. 暂无评论