Nico Foth
Nico Foth

Reputation: 19

Flutter Google Maps Popup "The Provided Api Key is invalid"

I'm building a Flutter App and added a screen to pick a specific location. This is the code for that screen:

class EventLocationPicker extends StatefulWidget {
  final String locationPlaceId;
  EventLocationPicker({required this.locationPlaceId});
  EventLocationPickerState createState() =>
      EventLocationPickerState(locationPlaceId: locationPlaceId);
}

class EventLocationPickerState extends State<EventLocationPicker> {
  String locationPlaceId;
  String originalLocationPlaceId;
  EventLocationPickerState({required this.locationPlaceId})
      : originalLocationPlaceId = locationPlaceId;

  final Completer<GoogleMapController> _controller = Completer();
  final GoogleGeocodingApi geoCoding =
      GoogleGeocodingApi(globals.GOOGLE_API_KEY);

  String locationAddress = "";
  String hintText = "Search for a location";
  LatLng startingPosition = LatLng(37.7749, -122.4194);
  Set<Marker> markers = {};

  Widget getFAB() {
    if (locationPlaceId != originalLocationPlaceId) {
      return FloatingActionButton(
          backgroundColor: Theme.of(context).primaryColor,
          child: Icon(Icons.check),
          onPressed: () {
            Navigator.pop(context,
                {"placeId": locationPlaceId, "address": locationAddress});
          });
    } else {
      return Container();
    }
  }

  Future<void> goToLocation(String placeId) async {
    locationPlaceId = placeId;
    final GoogleGeocodingResponse address =
        await geoCoding.placeGeocoding(placeId);
    final GoogleGeocodingLocation coordinates =
        address.results.first.geometry!.location;
    setState(() {
      locationPlaceId = placeId;
      locationAddress = address.results.first.formattedAddress;
      startingPosition = LatLng(coordinates.lat, coordinates.lng);
      markers.clear();
      markers.add(new Marker(
          markerId: MarkerId("eventLocation"),
          position: LatLng(coordinates.lat, coordinates.lng),
          infoWindow: InfoWindow(title: "Location", snippet: locationAddress)));
      hintText = locationAddress;
    });
  }

  Future<void> getPlaceById(String placeId) async {
    if (placeId != "") {
      return;
    }
    final GoogleGeocodingResponse response =
        await geoCoding.placeGeocoding(placeId);
    GoogleGeocodingResult result = response.results.first;
    locationPlaceId = result.placeId;
    locationAddress = result.formattedAddress;
    startingPosition = LatLng(
      result.geometry!.location.lat,
      result.geometry!.location.lng,
    );
    markers.clear();
    markers.add(new Marker(
      markerId: MarkerId("eventLocation"),
      position: LatLng(
        result.geometry!.location.lat,
        result.geometry!.location.lng,
      ),
      infoWindow: InfoWindow(
        title: "Location",
        snippet: locationAddress,
      ),
    ));
  }

  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          leading: BackButton(),
          title: Text("Event Location"),
          backgroundColor: Theme.of(context).primaryColor,
        ),
        floatingActionButton: getFAB(),
        floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
        body: FutureBuilder(
            future: getPlaceById(locationPlaceId),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (snapshot.connectionState != ConnectionState.done) {
                return Center(
                    child: CircularProgressIndicator(
                        color: Theme.of(context).primaryColor));
              } else {
                return Column(children: [
                  GooglePlaceAutoCompleteTextField(
                    isLatLngRequired: true,
                    googleAPIKey: globals.GOOGLE_API_KEY,
                    textEditingController: TextEditingController(),
                    debounceTime: 1000,
                    inputDecoration: InputDecoration(
                      hintText: hintText,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                      ),
                    ),
                    itemClick: (prediction) {
                      goToLocation(prediction.placeId!);
                    },
                  ),
                  Flexible(
                      child: GoogleMap(
                    zoomControlsEnabled: false,
                    markers: markers,
                    initialCameraPosition: CameraPosition(
                      target: startingPosition,
                      zoom: 14,
                    ),
                    onMapCreated: (GoogleMapController controller) {
                      if (!_controller.isCompleted) {
                        _controller.complete(controller);
                      }
                    },
                  ))
                ]);
              }
            }));
  }
}

Sometimes, after picking a location through the GooglePlaceAutoCompleteTextField, a pop up shows up at the bottom of the screen. This only happens sometimes and I can't find the pattern.

enter image description here

I tried to pin point the exact thing that is happening, but I'm still unsure. It seems like it's the Geocoding Api, because my Cloud Dashboard shows some faulty requests, but in my code it's not GoogleGeocodingApi.placeGeocoding. I debugged it and it always returns a message with status OK, even if the popup appears.

I also have no error messages in the debugger console. To be totally honest, I don't know what do anymore, especially because it only happens sometimes.

Upvotes: 0

Views: 305

Answers (1)

scottynoshotty
scottynoshotty

Reputation: 43

Adding this parameter fixed it for me:

isLatLngRequired: false,

Upvotes: 1

Related Questions