Flutter: show Circularprogressindicator while build Googlemap - google-maps

I want to show circularprogressindicator() until Googlemap build is finished.
I used FutureBuilder, but it didn't work.
my code
Container(
height:100,
child: FutureBuilder(
future: googlemap()
builder: (context, snapshot){
if(snapshot.hasdata){
return snapshot.data;
}
else{
return CircularProgressIndicator();
}
}
)
)
Futurbuilder
Futur<Widget> googlemap() async{
Completer<GoogleMapController> _controller = Completer();
return await Googlemap(
mapType: MapType.normal,
initialCameraPosition: CameraPosition(
target: LatLng(XX.XXXXXX, XXX.XXXXXX),
zoom: 17.0
)
onMapCreated: (GoogleMapController controller){
_controller.complete(controller);
},
myLocationEnabled: false,
myLocationButtonEnabled: false,
compassEnabled: false,
zoomGesturesEnabled: false,
rotateGesturesEnabled: false,
scrollGesturesEnabled: false,
tiltGesturesEnabled: false,
markers: Set<Marker>.of(_markers)
)
}
result
can i get some tips in here?

I haven't solved it yet, but I found an alternative.
my solution
bool splash = false;
#override
void initState() {
// TODO: implement initState
super.initState();
Future.delayed(Duration(seconds: 2), (){
setState(() {
splash = true;
});
});
}
Widget
#override
Widget build(BuildContext context) {
return splash ? SafeArea(
child: ListView(
children: [
//googlemap1(),
//googlemap2(),
//googlemap3(),
//googlemap4(),
],
),
) : Container(
child: Center(
child: CircularProgressIndicator()
),
);
}
please let me know if there is a better way than this.

Related

How to perform a text search over JSON data in Flutter?

I am working on an application which requires to fetch some JSON data from firebase storage and then a user can perform a search over it. But, my search query isn't working properly and I get one error when I perform the search multiple times.
I have first uploaded the data to firebase storage and then fetched it. The search is working sometimes only. I cannot figure out what is wrong with the code.
Here is the complete code
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'dart:convert';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Contacts Demo',
debugShowCheckedModeBanner: false,
home: StorageUpload(),
);
}
}
class StorageUpload extends StatefulWidget {
#override
StorageUploadState createState() => new StorageUploadState();
}
class StorageUploadState extends State<StorageUpload> {
var rows = [];
String query = '';
TextEditingController tc;
#override
void initState() {
super.initState();
tc = TextEditingController();
rows = [
{
'contact_name': 'Test User 1',
'contact_phone': '066 560 4900',
},
{
'contact_name': 'Test User 2',
'contact_phone': '066 560 7865',
},
{
'contact_name': 'Test User 3',
'contact_phone': '906 500 4334',
}
];
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(
"Delivero Contacts",
style: new TextStyle(
color: Colors.white,
),
),
),
body: Container(
color: Colors.white,
padding: EdgeInsets.all(10),
child: Stack(
children: [
Column(
children: [
Padding(
padding: const EdgeInsets.all(10.0),
child: TextField(
controller: tc,
decoration: InputDecoration(hintText: 'Search...'),
onChanged: (v) {
setState(() {
query = v;
});
},
),
),
Container(
color: Colors.white,
child: ListView.builder(
shrinkWrap: true,
itemCount: rows.length,
itemBuilder: (con, ind) {
return query.isEmpty
? ListTile(
title: Text(rows[ind]['contact_name']),
subtitle: Text(rows[ind]['contact_phone']),
onTap: () {
setState(() {
tc.text = rows[ind]['contact_name'];
query = rows[ind]['contact_name'];
});
},
)
: rows[ind]['contact_name']
.toString()
.toLowerCase()
.contains(query.toLowerCase()) ||
rows[ind]['contact_phone']
.toString()
.toLowerCase()
.contains(query.toLowerCase())
? ListTile(
title: Text(rows[ind]['contact_name']),
subtitle: Text(rows[ind]['contact_phone']),
onTap: () {
setState(() {
tc.text = rows[ind]['contact_name'];
query = rows[ind]['contact_name'];
});
},
)
: null;
},
),
),
],
),
],
),
),
);
}
}
Here is the error I am getting
════════ Exception caught by rendering library ═════════════════════════════════
The following assertion was thrown during performLayout():
'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 662 pos 16: 'indexOf(child) == index': is not true.
Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
https://github.com/flutter/flutter/issues/new?template=BUG.md
The relevant error-causing widget was
ListView
lib/main.dart:104
When the exception was thrown, this was the stack
#2 RenderSliverMultiBoxAdaptor.debugAssertChildListIsNonEmptyAndContiguous.<anonymous closure>
package:flutter/…/rendering/sliver_multi_box_adaptor.dart:662
#3 RenderSliverMultiBoxAdaptor.debugAssertChildListIsNonEmptyAndContiguous
package:flutter/…/rendering/sliver_multi_box_adaptor.dart:666
#4 RenderSliverList.performLayout
package:flutter/…/rendering/sliver_list.dart:282
#5 RenderObject.layout
package:flutter/…/rendering/object.dart:1767
#6 RenderSliverEdgeInsetsPadding.performLayout
package:flutter/…/rendering/sliver_padding.dart:135
...
The following RenderObject was being processed when the exception was fired: RenderSliverList#5c228 relayoutBoundary=up17 NEEDS-LAYOUT NEEDS-COMPOSITING-BITS-UPDATE
RenderObject: RenderSliverList#5c228 relayoutBoundary=up17 NEEDS-LAYOUT NEEDS-COMPOSITING-BITS-UPDATE
needs compositing
parentData: paintOffset=Offset(0.0, 0.0) (can use size)
constraints: SliverConstraints(AxisDirection.down, GrowthDirection.forward, ScrollDirection.idle, scrollOffset: 0.0, remainingPaintExtent: Infinity, crossAxisExtent: 372.7, crossAxisDirection: AxisDirection.right, viewportMainAxisExtent: Infinity, remainingCacheExtent: Infinity, cacheOrigin: 0.0)
geometry: SliverGeometry(scrollExtent: 224.0, paintExtent: 224.0, maxPaintExtent: 224.0, cacheExtent: 224.0)
scrollExtent: 224.0
paintExtent: 224.0
maxPaintExtent: 224.0
cacheExtent: 224.0
currently live children: 0 to 3
child with index 0: RenderIndexedSemantics#ea1e2 relayoutBoundary=up18
needs compositing
parentData: index=0; layoutOffset=0.0 (can use size)
constraints: BoxConstraints(w=372.7, 0.0<=h<=Infinity)
semantic boundary
size: Size(372.7, 56.0)
index: 0
child: RenderRepaintBoundary#17c6b relayoutBoundary=up19
needs compositing
parentData: <none> (can use size)
constraints: BoxConstraints(w=372.7, 0.0<=h<=Infinity)
layer: OffsetLayer#34eb7
engine layer: OffsetEngineLayer#a8a79
offset: Offset(0.0, 0.0)
size: Size(372.7, 56.0)
metrics: 0.0% useful (1 bad vs 0 good)
diagnosis: insufficient data to draw conclusion (less than five repaints)
child: RenderSemanticsAnnotations#2ecd5 relayoutBoundary=up20
parentData: <none> (can use size)
constraints: BoxConstraints(w=372.7, 0.0<=h<=Infinity)
size: Size(372.7, 56.0)
child: RenderMouseRegion#9a9a8 relayoutBoundary=up21
parentData: <none> (can use size)
constraints: BoxConstraints(w=372.7, 0.0<=h<=Infinity)
size: Size(372.7, 56.0)
listeners: enter, exit
cursor: SystemMouseCursor(click)
child with index 3: RenderIndexedSemantics#96641 relayoutBoundary=up18
needs compositing
parentData: index=3; layoutOffset=168.0 (can use size)
constraints: BoxConstraints(w=372.7, 0.0<=h<=Infinity)
semantic boundary
size: Size(372.7, 56.0)
index: 3
child: RenderRepaintBoundary#13951 relayoutBoundary=up19
needs compositing
parentData: <none> (can use size)
constraints: BoxConstraints(w=372.7, 0.0<=h<=Infinity)
layer: OffsetLayer#768be
engine layer: OffsetEngineLayer#51b91
offset: Offset(0.0, 168.0)
size: Size(372.7, 56.0)
metrics: 0.0% useful (1 bad vs 0 good)
diagnosis: insufficient data to draw conclusion (less than five repaints)
child: RenderSemanticsAnnotations#77b2c relayoutBoundary=up20
parentData: <none> (can use size)
constraints: BoxConstraints(w=372.7, 0.0<=h<=Infinity)
size: Size(372.7, 56.0)
child: RenderMouseRegion#9ae66 relayoutBoundary=up21
parentData: <none> (can use size)
constraints: BoxConstraints(w=372.7, 0.0<=h<=Infinity)
size: Size(372.7, 56.0)
listeners: enter, exit
cursor: SystemMouseCursor(click)
════════════════════════════════════════════════════════════════════════════════
I am a Flutter noob. How can I perform a full-text search over different JSON field from the data fetched from firebase storage? Any help would be amazing. Thanks for your time!
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Contacts Demo',
debugShowCheckedModeBanner: false,
home: StorageUpload(),
);
}
}
class StorageUpload extends StatefulWidget {
#override
StorageUploadState createState() => new StorageUploadState();
}
class StorageUploadState extends State<StorageUpload> {
List<Map<String,dynamic>> original=[],duplicate=[];
String query = '';
TextEditingController tc;
StreamController<List<Map<String,dynamic>>> controller = StreamController<List<Map<String,dynamic>>>();
#override
void initState() {
super.initState();
tc = TextEditingController();
original = [
{
'contact_name': 'Test User 1',
'contact_phone': '066 560 4900',
},
{
'contact_name': 'Test User 2',
'contact_phone': '066 560 7865',
},
{
'contact_name': 'Test User 3',
'contact_phone': '906 500 4334',
}
];
duplicate.addAll(original);
controller.sink.add(duplicate);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(
"Delivero Contacts",
style: new TextStyle(
color: Colors.white,
),
),
),
body: Container(
color: Colors.white,
padding: EdgeInsets.all(10),
child: Stack(
children: [
Column(
children: [
Padding(
padding: const EdgeInsets.all(10.0),
child: TextField(
controller: tc,
decoration: InputDecoration(hintText: 'Search...'),
onChanged: (v) {
if(v.isEmpty){
duplicate = original;
controller.sink.add(duplicate);
return;
}
//If your data is a Map object you can use toString()
//and avoid checking both fields
duplicate = original.where((m)=>
m['contact_name'].toString().toLowerCase().contains(v.toLowerCase())||
m['contact_phone'].toString().toLowerCase().contains(v.toLowerCase())).toList();
controller.sink.add(duplicate);
},
),
),
Container(
color: Colors.white,
child: StreamBuilder<Object>(
stream: controller.stream,
builder: (context, snapshot) {
return ListView.builder(
shrinkWrap: true,
itemCount: duplicate.length,
itemBuilder: (con, ind) {
return query.isEmpty
? ListTile(
title: Text(duplicate[ind]['contact_name']),
subtitle: Text(duplicate[ind]['contact_phone']),
onTap: () {
setState(() {
tc.text = duplicate[ind]['contact_name'];
query = duplicate[ind]['contact_name'];
});
},
)
: duplicate[ind]['contact_name']
.toString()
.toLowerCase()
.contains(query) ||
duplicate[ind]['contact_phone']
.toString()
.toLowerCase()
.contains(query)
? ListTile(
title: Text(duplicate[ind]['contact_name']),
subtitle: Text(duplicate[ind]['contact_phone']),
onTap: () {
setState(() {
tc.text = duplicate[ind]['contact_name'];
query = duplicate[ind]['contact_name'];
});
},
):null;
},
);
}
),
),
],
),
],
),
),
);
}
#override
void dispose(){
controller?.close();
super.dispose();
}
}
I slightly changed your code to make a working sample.
I added a results List object and I moved the "query.isEmpty" check before the ListView:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Contacts Demo',
debugShowCheckedModeBanner: false,
home: StorageUpload(),
);
}
}
class StorageUpload extends StatefulWidget {
#override
StorageUploadState createState() => new StorageUploadState();
}
class StorageUploadState extends State<StorageUpload> {
List results = [];
var rows = [];
String query = '';
TextEditingController tc;
#override
void initState() {
super.initState();
tc = TextEditingController();
rows = [
{
'contact_name': 'Test User 1',
'contact_phone': '066 560 4900',
},
{
'contact_name': 'Test User 2',
'contact_phone': '066 560 7865',
},
{
'contact_name': 'Test User 3',
'contact_phone': '906 500 4334',
}
];
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(
"Delivero Contacts",
style: new TextStyle(
color: Colors.white,
),
),
),
body: Container(
color: Colors.white,
padding: EdgeInsets.all(10),
child: Stack(
children: [
Column(
children: [
Padding(
padding: const EdgeInsets.all(10.0),
child: TextField(
controller: tc,
decoration: InputDecoration(hintText: 'Search...'),
onChanged: (v) {
setState(() {
query = v;
setResults(query);
});
},
),
),
Container(
color: Colors.white,
child: query.isEmpty
? ListView.builder(
shrinkWrap: true,
itemCount: rows.length,
itemBuilder: (con, ind) {
return ListTile(
title: Text(rows[ind]['contact_name']),
subtitle: Text(rows[ind]['contact_phone']),
onTap: () {
setState(() {
tc.text = rows[ind]['contact_name'];
query = rows[ind]['contact_name'];
setResults(query);
});
},
);
},
)
: ListView.builder(
shrinkWrap: true,
itemCount: results.length,
itemBuilder: (con, ind) {
return ListTile(
title: Text(results[ind]['contact_name']),
subtitle: Text(results[ind]['contact_phone']),
onTap: () {
setState(() {
tc.text = results[ind]['contact_name'];
query = results[ind]['contact_name'];
setResults(query);
});
},
);
},
),
),
],
),
],
),
),
);
}
void setResults(String query) {
results = rows
.where((elem) =>
elem['contact_name']
.toString()
.toLowerCase()
.contains(query.toLowerCase()) ||
elem['contact_phone']
.toString()
.toLowerCase()
.contains(query.toLowerCase()))
.toList();
}
}

get data snapshot to location latitude longitude

I succed for get data from firestore with this code:
return new Scaffold(
body: Column(
children: <Widget>[
StreamBuilder(
stream: Firestore.instance.collection("location").snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData)
return Text("Loading Data.. Please Wait");
return
Container(
child: GoogleMap(
mapType: MapType.normal,
initialCameraPosition: CameraPosition(
target: LatLng("${snapshot.data.documents[0]['latitude']}", "${snapshot.data.documents[0]['longitude']}"),
zoom: 12.0
),
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
),
);
},
),
],
),
);
but I not really uderstand how to put value in LatLng(error in here), that is error.
anybody have the idea for that problem, appreciate for your help.
From the google_maps documentation, I can see you have to pass 2 double values to LatLng constructor.
Try the code below:
return new Scaffold(
body: Column(
children: <Widget>[
StreamBuilder(
stream: Firestore.instance.collection("location").snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData)
return Text("Loading Data.. Please Wait");
return
Container(
child: GoogleMap(
mapType: MapType.normal,
initialCameraPosition: CameraPosition(
target: LatLng(double.parse("${snapshot.data.documents[0]['latitude']}"), double.parse("${snapshot.data.documents[0]['longitude']}")),
zoom: 12.0
),
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
),
);
},
),
],
),
);
The difference is that I used double.parse() to convert your data to double and then I pass it to the LatLng constructor.

Close drawer automatically return MaterialApp and Scaffold black screen after Navigator.pop(context);

Hy Guys I'm trying try to close drawer inside material app but it is not working. My code:
#override
Widget build(BuildContext context) {
return MaterialApp(
home: currentLocation == null ? Container(
alignment: Alignment.center,
child: Center(
child: CircularProgressIndicator(),
),
):
Scaffold(
drawer: Drawer(
child: ListView(
children: <Widget>[
ListTile(
leading: CircleAvatar(),
title: Text("test app"),
subtitle: Text("nn"),
),
ListTile(leading: Icon(Icons.multiline_chart), title: Text("check gps.."),
onTap: () {
_checkgps();
Navigator.pop(context);
}
),
appBar: AppBar(
title: Text('test app'),
),
body: GoogleMap(
initialCameraPosition:
CameraPosition(target: LatLng(currentLocation.latitude,
currentLocation.longitude), zoom: 17),
onMapCreated: _onMapCreated,
mapType: _currentMapType,
compassEnabled: true,
myLocationEnabled: true,
polylines: Set<Polyline>.of(_mapPolylines.values),
markers: Set<Marker>.of(markers.values),
)
);
}
But when i press list item 1 ( checkgps ) Navigator.pop(context); going to black screen and not see google maps. Any idea?
I am assuming that you are calling this widget directly from you run app and because of that it is causing error.
Your appbar was also at wrong place.
checkout below code.
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Scaffold(body: DeleteWidget()),
);
}
}
class DeleteWidget extends StatefulWidget {
const DeleteWidget({Key key}) : super(key: key);
#override
_DeleteWidgetState createState() => _DeleteWidgetState();
}
class _DeleteWidgetState extends State<DeleteWidget> {
#override
Widget build(BuildContext context) {
return currentLocation == null
? Container(
alignment: Alignment.center,
child: Center(
child: CircularProgressIndicator(),
),
)
: Scaffold(
drawer: Drawer(
child: ListView(children: <Widget>[
ListTile(
leading: CircleAvatar(),
title: Text("test app"),
subtitle: Text("nn"),
),
ListTile(
leading: Icon(Icons.multiline_chart),
title: Text("check gps.."),
onTap: () {
_checkgps();
Navigator.pop(context);
}),
]),
),
appBar: AppBar(
title: Text('test app'),
),
body: GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(
currentLocation.latitude, currentLocation.longitude),
zoom: 17),
onMapCreated: _onMapCreated,
mapType: _currentMapType,
compassEnabled: true,
myLocationEnabled: true,
polylines: Set<Polyline>.of(_mapPolylines.values),
markers: Set<Marker>.of(markers.values),
),
);
}
}
The problem is that you are not popping the Drawer's context, you are popping the MaterialApp's context.
Also it is a good idea to split your app into small piece of widgets, so your drawer content must be placed in another widget. I've made these changes, try out this code:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Scaffold(body: DeleteWidget()),
);
}
}
class DeleteWidget extends StatefulWidget {
const DeleteWidget({Key key}) : super(key: key);
#override
_DeleteWidgetState createState() => _DeleteWidgetState();
}
class _DeleteWidgetState extends State<DeleteWidget> {
#override
Widget build(BuildContext context) {
return currentLocation == null
? Container(
alignment: Alignment.center,
child: Center(
child: CircularProgressIndicator(),
),
)
: Scaffold(
drawer: _DrawerContent(),
appBar: AppBar(
title: Text('test app'),
),
body: GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(
currentLocation.latitude, currentLocation.longitude),
zoom: 17),
onMapCreated: _onMapCreated,
mapType: _currentMapType,
compassEnabled: true,
myLocationEnabled: true,
polylines: Set<Polyline>.of(_mapPolylines.values),
markers: Set<Marker>.of(markers.values),
),
);
}
}
class _DrawerContent extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Drawer(
child: ListView(children: <Widget>[
ListTile(
leading: CircleAvatar(),
title: Text("test app"),
subtitle: Text("nn"),
),
ListTile(
leading: Icon(Icons.multiline_chart),
title: Text("check gps.."),
onTap: () {
_checkgps();
Navigator.pop(context);
}),
]),
);
}
}
With the Drawer content in another widget when you call Navigator.pop(context); it will pop the drawer context not the Page context where the Drawer is.
Instead of calling navigator.pop you can use
Navigator.of(context).maybePop();

How to get all detail of address when i am put mark on google map. and then it will fill up in text box in flutter

I want to put a marker on the map and when I put marker it will get that address and filled into the textbox.
like I've mentioned in this images when I put a marker and then click on show address it will take that address and filled into textboxes. Hope you understand the question. if any query then let me know. I need help please help me. because I am very much stuck in this problem.
Here is some code for google maps.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:tudo/src/styles/colors.dart';
import 'package:tudo/src/utils/navigation_helper.dart';
import 'package:tudo/src/widgets/google_map.dart';
const kGoogleApiKey = "API_KEY";
class BspAddressmapscreen extends StatefulWidget {
BspAddressmapscreen({Key key}) : super(key: key);
#override
_BspAddressmapscreenState createState() => _BspAddressmapscreenState();
}
class _BspAddressmapscreenState extends State<BspAddressmapscreen> {
final homeScaffoldKey = GlobalKey<ScaffoldState>();
Completer<GoogleMapController> _controller = Completer();
#override
void initState() {
super.initState();
}
double zoomVal = 5.0;
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () {
NavigationHelper.navigatetoBack(context);
}),
centerTitle: true,
title: Text("Business Address Detail"),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
onPressed: () {},
),
],
),
bottomNavigationBar: Container(
color: Colors.transparent,
height: 56,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
new FlatButton.icon(
icon: Icon(Icons.arrow_back_ios),
label: Text('Show Address'),
textColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(7),
),
onPressed: () async {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BspAddressmapscreen()));
},
),
],
),
),
body: Container(
height: double.infinity,
width: double.infinity,
child: Stack(
children: <Widget>[
_searchbar(),
_buildGoogleMap(context),
_zoomminusfunction(),
_zoomplusfunction(),
],
),
),
);
}
Widget _zoomminusfunction() {
return Align(
alignment: Alignment.topLeft,
child: IconButton(
icon: Icon(FontAwesomeIcons.searchMinus, color: Color(0xff008080)),
onPressed: () {
zoomVal--;
_minus(zoomVal);
}),
);
}
Widget _zoomplusfunction() {
return Align(
alignment: Alignment.topRight,
child: IconButton(
icon: Icon(FontAwesomeIcons.searchPlus, color: Color(0xff008080)),
onPressed: () {
zoomVal++;
_plus(zoomVal);
}),
);
}
Future<void> _minus(double zoomVal) async {
final GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(target: LatLng(40.712776, -74.005974), zoom: zoomVal)));
}
Future<void> _plus(double zoomVal) async {
final GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(target: LatLng(40.712776, -74.005974), zoom: zoomVal)));
}
Widget _buildGoogleMap(BuildContext context) {
return Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: GoogleMap(
mapType: MapType.normal,
initialCameraPosition:
CameraPosition(target: LatLng(40.712776, -74.005974), zoom: 12),
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
),
);
}
Widget _searchbar() {
return Positioned(
top: 50.0,
right: 15.0,
left: 15.0,
child: Container(
height: 50.0,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0), color: Colors.white),
child: TextField(
decoration: InputDecoration(
hintText: 'Enter Address',
border: InputBorder.none,
contentPadding: EdgeInsets.only(left: 15.0, top: 15.0),
suffixIcon: IconButton(
icon: Icon(Icons.search),
//onPressed: searchandNavigate,
onPressed: () {},
iconSize: 30.0)),
onChanged: (val) {
setState(() {
// searchAddr = val;
});
},
),
),
);
}
}
Use below code to plot marker and get an address on button click, also use geocoder to get the address from latlng
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
const kGoogleApiKey = "API_KEY";
class BspAddressmapscreen extends StatefulWidget {
BspAddressmapscreen({Key key}) : super(key: key);
#override
_BspAddressmapscreenState createState() => _BspAddressmapscreenState();
}
class _BspAddressmapscreenState extends State<BspAddressmapscreen> {
final homeScaffoldKey = GlobalKey<ScaffoldState>();
Completer<GoogleMapController> _controller = Completer();
#override
void initState() {
super.initState();
}
double zoomVal = 5.0;
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () {
/*NavigationHelper.navigatetoBack(context);*/
}),
centerTitle: true,
title: Text("Business Address Detail"),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
onPressed: () {},
),
],
),
bottomNavigationBar: Container(
color: Colors.transparent,
height: 56,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
new FlatButton.icon(
icon: Icon(Icons.arrow_back_ios),
label: Text('Show Address'),
textColor: Colors.blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(7),
),
onPressed: () {
getUserLocation();
},
),
],
),
),
body: Container(
height: double.infinity,
width: double.infinity,
child: Stack(
children: <Widget>[
_searchbar(),
_buildGoogleMap(context),
_zoomminusfunction(),
_zoomplusfunction(),
],
),
),
);
}
getUserLocation() async {
markers.values.forEach((value) async {
print(value.position);
// From coordinates
final coordinates =
new Coordinates(value.position.latitude, value.position.longitude);
var addresses = await Geocoder.google(kGoogleApiKey)
.findAddressesFromCoordinates(coordinates);
print("Address: ${addresses.first.featureName}");
});
}
Widget _zoomminusfunction() {
return Align(
alignment: Alignment.topLeft,
child: IconButton(
icon: Icon(Icons.remove, color: Color(0xff008080)),
onPressed: () {
zoomVal--;
_minus(zoomVal);
}),
);
}
Widget _zoomplusfunction() {
return Align(
alignment: Alignment.topRight,
child: IconButton(
icon: Icon(Icons.add, color: Color(0xff008080)),
onPressed: () {
zoomVal++;
_plus(zoomVal);
}),
);
}
Future<void> _minus(double zoomVal) async {
final GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(target: LatLng(40.712776, -74.005974), zoom: zoomVal)));
}
Future<void> _plus(double zoomVal) async {
final GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(target: LatLng(40.712776, -74.005974), zoom: zoomVal)));
}
Map<MarkerId, Marker> markers = <MarkerId, Marker>{};
Widget _buildGoogleMap(BuildContext context) {
return Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: GoogleMap(
mapType: MapType.normal,
initialCameraPosition:
CameraPosition(target: LatLng(40.712776, -74.005974), zoom: 12),
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
markers: Set<Marker>.of(markers.values),
onLongPress: (LatLng latLng) {
// creating a new MARKER
final MarkerId markerId = MarkerId('4544');
final Marker marker = Marker(
markerId: markerId,
position: latLng,
);
setState(() {
markers.clear();
// adding a new marker to map
markers[markerId] = marker;
});
},
),
);
}
Widget _searchbar() {
return Positioned(
top: 50.0,
right: 15.0,
left: 15.0,
child: Container(
height: 50.0,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0), color: Colors.white),
child: TextField(
decoration: InputDecoration(
hintText: 'Enter Address',
border: InputBorder.none,
contentPadding: EdgeInsets.only(left: 15.0, top: 15.0),
suffixIcon: IconButton(
icon: Icon(Icons.search),
//onPressed: searchandNavigate,
onPressed: () {},
iconSize: 30.0,
),
),
onChanged: (val) {
setState(() {
// searchAddr = val;
});
},
),
),
);
}
}

Get and draw GoogleMap Marker from JSON file

My simple application that get marker information from local JSON files and draws them.
It look like clear but I got a problem, it is just drawing the map, not show the marker.
I have consulted many guidelines and have applied but failed.
I sure added assets: - assets/data.json on pubspec.yaml
This is my main.dart code
class _MyHomePageState extends State<MyHomePage> {
Future _future;
List<Marker> allMarkers = [];
Future<String> loadJson() async =>
await rootBundle.loadString('assets/data.json');
GoogleMapController _controller;
#override
void initState() {
_future = loadJson();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Stack(
children: <Widget>[
FutureBuilder(
future: _future,
builder: (context, snapshot) {
if (snapshot.hasData) {
for (var v in snapshot.data) {
allMarkers.add(Marker(
markerId: v['id'],
position: LatLng(v['x'], v['y']),
));
}
return Text(snapshot.data);
} else {
return CircularProgressIndicator();
}
}),
GoogleMap(
initialCameraPosition:
CameraPosition(target: LatLng(40.7128, -74.0060), zoom: 12.0),
markers: Set.from(allMarkers),
onMapCreated: mapCreated,
),
],
),
));
}
void mapCreated(controller) {
setState(() {
_controller = controller;
});
}
}
My data.json
[{
"rownum": 1,
"id": "E3E0D2C5-CB82-4AF3-8D5D-4CD323560F59",
"x": 40.7128,
"y": -74.0060,
}, {
"rownum": 2,
"id": "5FFB6736-7D1F-4B40-A397-32EB3128BC30",
"x": 41.7128,
"y": -71.0060,
}]