How to integrate with google maps in flutter? - google-maps

I started to develop with flutter and I want to use google_maps_flutter package.
I was going through medium post in order to add map to my app (https://medium.com/flutter-io/google-maps-and-flutter-cfb330f9a245).
I added this code in AppDelegate.m
#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"
#import "GoogleMaps/GoogleMaps.h"
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GMSServices provideAPIKey:#"******"];
[GeneratedPluginRegistrant registerWithRegistry:self];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
#end
and this to Info.plist
<key>io.flutter.embedded_views_preview</key>
<true/>
and this is the widget code:
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
GoogleMapController mapController;
final LatLng _center = const LatLng(45.521563, -122.677433);
void _onMapCreated(GoogleMapController controller) {
mapController = controller;
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Maps Sample App'),
backgroundColor: Colors.green[700],
),
body: GoogleMap(
onMapCreated: _onMapCreated,
options: GoogleMapOptions(
cameraPosition: CameraPosition(
target: _center,
zoom: 11.0,
),
),
),
),
);
}
}
As the example in the post, but unfortunately I get a screen with the google maps widget but not showing a map. like this: https://i.imgur.com/HGam5ac.jpg (I can't upload an image because low reputation, sorry :( ).
Is there a problem with the sdk? or there is something to change in the code?
Thank you for your help!!

I faced the same issue and spent some time figuring it out.
Please note it is not advisable to unrestrict your API key and should be a temporary solution.
First of all, you cannot use the Google Maps APIs if you have not enabled billing in your Google Cloud Platform account.
I fixed this issue by making sure my API Key was not restricted.
I deleted my previous API key and created a new API key but this time I did not restrict the API key.
The map loaded correctly afterwards.
If you intend to use the geolocation services, it might help to add to your ios/Runner/Info.plist file the code below
<key>NSLocationWhenInUseUsageDescription</key>
<string>Reason for requesting location permission</string>
If you do not know how to create the API keys follow this link Get API Key.
This is how my API key configuration looks like
And this is how my maps page in my app looks like

Related

Flutter for Linux: display HTML asset file in the app

Is there currently in flutter any way to display/load an HTML file from the assets folder in an application for linux? I have been researching for a while but to no avail. I have no code example, since all the approaches I have found are targeted for android and iOS. If anyone knows of an accessible way or a workaround, thank you in advance.
For Linux (desktop) looks like the flutter_html package works too (even if it is still not indicated at pub.dev). So what I did it's the following: I loaded the file from the rootBundle, that is, from my assets folder and parsed it to a Document object. After that, I just got the outerHtml String and passed it as a parameter to an Html Widget from the flutter_html package, as mentioned.
So if you want to give this a try, make sure you have your assets folder correctly set and store the HTML file in it. I took an example HTML file from: https://filesamples.com/formats/html.
After that, make sure you set your dependencies at pubspec.yaml (choose the versions that fit you best):
dependencies:
flutter:
sdk: flutter
html: any # Add this
flutter_html: ^1.3.0 # Add this
Still at pubspec.yaml: set the reference to your assets folder.
flutter:
uses-material-design: true
assets: # Add this
- assets/ # Add this
Then place this code in your main.dart and run it:
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:html/parser.dart' show parse;
import 'package:html/dom.dart' as dom;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Load on Linux for desktop'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
void initState() {
getHtml();
super.initState();
}
Future<dom.Document> getHtml() async {
return parse(await rootBundle.loadString('assets/sample1.html'));
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder<dom.Document>(
future: getHtml(),
builder:
(BuildContext context, AsyncSnapshot<dom.Document> snapshot) {
if (snapshot.hasData) {
return Html(data: snapshot.data.outerHtml);
} else {
return Center(
child: Text("Loading"),
);
}
}),
);
}
}
If needed, these are my OS details.
NAME="Ubuntu" VERSION="18.04.5 LTS (Bionic Beaver)" ID=ubuntu
ID_LIKE=debian PRETTY_NAME="Ubuntu 18.04.5 LTS" VERSION_ID="18.04"

Having an issue running Maps app on flutter-API key not found

**So I'm having an issue figuring out the solution for this issue.
I'm trying to run a simple map app and all I can see is a blank screen.
After spending several hours online trying to find similar post I couldn't manage to fix it.
Map SDK enabled for android as well as for IOS.
Maps_Enabled_Picture
this is the manifest part**
<application
android:name="io.flutter.app.FlutterApplication"
android:label="integrativeUI2020"
android:icon="#mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="#style/NormalTheme"
/>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyDkKQaxxxxlIhmp1nmQrVQHnE"/>
the code is
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
GoogleMapController mapController;
final LatLng _center = const LatLng(45.521563, -122.677433);
void _onMapCreated(GoogleMapController controller) {
mapController = controller;
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Maps Sample App'),
backgroundColor: Colors.green[700],
),
body: GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(
target: _center,
zoom: 11.0,
),
),
),
);
}
}
For some uncleared reason I see in the console this error
java.lang.RuntimeException: API key not found. Check that <meta-data android:name="com.google.android.geo.API_KEY" android:value="your API key"/> is in the <application> element of AndroidManifest.xml

Flutter GoogleMap Provider Context problem

I have a basic stateful app, with a GoogleMap base, which opens a BottomSheet on FloatingActionButton press. This is used as a settings tab to change/filter some lists which are then used by the map. My Provider is setup and values can be read/saved from both the GoogleMap dart file, and the BottomSheet dart file.
My main problem is how to provide context to the Provider.of() when not in the Widget Tree. For example, the GoogleMap runs onMapCreated: _onMapCreated, when finished loading. From within that function I want to pull a value from the Provider.of() a String, which tells me which list to use (which then populates the markers).
Things I'm trying to do:
onMapCreated() pull value from the Provider (which is later used in a DB sqflite query)
The bottomsheet needs to callback and updateMarkers() somehow, providing correct context
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
GoogleMapController mapController;
void _onMapCreated(GoogleMapController controller) {
mapController = controller;
print(Provider.of<MyAppStateContainer>(context, listen:false).getSomeValue); <---- Doesn't work
...
}
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider<MyAppStateContainer>(
create: (contextooo) => MyAppStateContainer(),
child: MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My Map'),
backgroundColor: Colors.green[700],
),
//Put in a stack widget so can layer other widgets on top of map widget
body: Stack(
children: <Widget>[
//Builder so we can get a CTX made, and then Provider.of() finds the Provider
Builder(
builder: (context) => GoogleMap(
mapType: Provider.of<MyAppStateContainer>(context).getMapType, <--- Works fine
markers: _markers,
onMapCreated: _onMapCreated,
...
}
Provider:
class MyAppStateContainer extends ChangeNotifier {
MyAppStateContainer();
MapType _mapType = MapType.terrain;
String _someValue;
MapType get getMapType => _mapType;
String get getSomeValue => _someValue;
}
I've tried all sorts of combinations of passing back BuildContext context but sadly I'm forever getting this error about the Widget Tree:
Unhandled Exception: Error: Could not find the correct Provider<MyAppStateContainer> above this MyApp Widget
The problem is that within _onMapCreated, you are trying to access the Provider using the context of MyApp, which is higher up the hierarchy of widgets than the Provider itself.
Convert your home widget (the Scaffold and everything below it) into a separate StatefulWidget and everything should start working, as you'll be using the context of the new widget, which is lower down the hierarchy of widgets than the Provider.

Flutter: how to keep widget with Google Map unchanged?

I am using Google Maps for Flutter widget.
In my app map is displayed via one of the tabs of BottomNavigationBar.
And I have the following problem:
user is on Map's tab
user changes tab (by tapping on another one)
[PROBLEM] when user returns on Map's tab map redraws.
I would like to keep map as it is when user leaves Map's tab, so he can continue to work with it when he returns to it later on.
Tried to:
use PageStorage - without success.
make something like Singletone of Map's state - without success.
use AutomaticKeepAliveClientMixin (saw here), which looked promising, but still without success.
(I admit that I could have done something wrong)
Code of last attempt:
class MapScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() => MapScreenState();
}
class MapScreenState extends State<MapScreen> with AutomaticKeepAliveClientMixin {
GoogleMapController mapController;
#override
bool get wantKeepAlive => true;
#override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
appBar: AppBar(
title: const Text("Map"),
),
body: GoogleMap(
onMapCreated: _onMapCreated,
)
);
}
void _onMapCreated(GoogleMapController controller) {
mapController = controller;
updateKeepAlive();
}
}
So, I just need a way to either keep MapScreen alive and unchanged, or to store its state somehow and restore it when user returns to MapScreen. Or something else which will solve the problem.
Use IndexedStack
For example:
Class _ExamplePageState extends State<ExamplePage> {
int _bottomNavIndex = 0;
final List<Widget> _children = [
WidgetOne(),
WidgetTwo(),
GoogleMap(),
]
#override
Widget build(BuildContext context) {
return Scaffold(
body: IndexedStack(
index: _bottomNavIndex,
children: _children,
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _bottomNavIndex,
onTap: (index) {
if (_bottomNavIndex == index) return;
setState(() {
_bottomNavIndex = index;
});
}
items: [ ... ]
),
);
}
}
Widget always rebuild after you change from page to page, so, try this , use a variable for GoogleMap and reuse if it's different from null.
GoogleMap _map;
#override
Widget build(BuildContext context) {
if (_map == null){
_map = GoogleMap(
onMapCreated: _onMapCreated,
);
}
return Scaffold(
appBar: AppBar(
title: const Text("Map"),
),
body:_map,
);
}
I was just having this same problem and the mixin solved it. I think you've just missed enter the type of mixin at the end of its declaration.
class MapScreenState extends State<MapScreen> with AutomaticKeepAliveClientMixin<MapScreenState>
see this thread if anything.
AutomaticKeepAliveClientMixin
To
AutomaticKeepAliveClientMixin<MapScreenState>

Flutter how to bring front widget

is there anyway that we can bring the widget front of the screen and let other widget behind the screen?, tried Stack widget but not working, I'm implementing a Google Maps using flutter google_maps_flutter library, see code below:
import 'dart:ui' as ui;
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:flutter/material.dart';
final size = MediaQueryData.fromWindow(ui.window).size;
final GoogleMapOverlayController controller =
GoogleMapOverlayController.fromSize(
width: size.width,
height: size.height,
);
class GoogleMapView extends StatefulWidget {
_GoogleMapViewState createState() => _GoogleMapViewState();
}
class _GoogleMapViewState extends State<GoogleMapView> {
final mapController = controller.mapController;
final Widget mapWidget = GoogleMapOverlay(controller: controller);
#override
void initState() {
super.initState();
GoogleMapController.init();
}
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Container(
alignment: Alignment.center,
height: size.height,
width: size.width,
child: new Stack(
children: <Widget>[
mapWidget,
new Container(
height: 100.0,
alignment: Alignment.topCenter,
child: new Text('Hey there!'),
)
],
),
),
navigatorObservers: <NavigatorObserver>[controller.overlayController],
);
}
}
See the screenshot which it should have a red color on top of the google map aligned in the top corner of the screen. How to implement this using flutter Stack widget, I'm having problem with this since yesterday and couldn't find any solution, can anyone help me with this? thanks!
Stack works fine for that purpose, it's just that the Google Maps plugin is rendering a native view that can't yet be overlayed by something else.
You might want to follow https://github.com/flutter/flutter/issues/73
See especially this comment https://github.com/flutter/flutter/issues/73#issuecomment-417040742