How to draw polyline on google map in flutter - google-maps

I'm trying to draw polyline between two location with using flutter google map library.
// here the Map Body
body:Container(
child: GoogleMap(
myLocationEnabled: true,
mapType: MapType.hybrid,
onMapCreated: (GoogleMapController controller){
mapController=controller;
},
initialCameraPosition: CameraPosition(
target: center,
zoom: 11.0
),
markers: markers,
),
),

I assume you've found a solution to this but just in case someone else find themselves here...
Here's how you'd do that.
List<Polyline> _polyLine = [];
_polyLine.add(Polyline(
polylineId: PolylineId("route1"),
color: Colors.blue,
patterns: [
PatternItem.dash(20.0),
PatternItem.gap(10)
],
width: 3,
points: [
LOCATION_A,
LOCATION_B,
],
));
.
.
.
.
GoogleMap(
myLocationEnabled: true,
mapType: MapType.hybrid,
onMapCreated: (GoogleMapController controller){
mapController=controller;
},
initialCameraPosition: CameraPosition(
target: center,
zoom: 11.0
),
markers: markers,
polylines: _polyLine.toSet(),
),

Use inside Google() widget polygons and try like this
GoogleMap(
markers: markersAr,
myLocationEnabled: true,
initialCameraPosition: CameraPosition(
target: LatLng(6.843369, 79.874814),
zoom: 12.99,
),
polygons: Set<Polygon>.of(<Polygon>[
Polygon(
polygonId: PolygonId('area'),
points: getPoints(),
geodesic: true,
strokeColor: Colors.red.withOpacity(0.6),
strokeWidth: 5,
fillColor: Colors.redAccent.withOpacity(0.1),
visible: true),
]),)
put your coordinate into
getPoint()
getPoints() {
return [
LatLng(6.862472, 79.859482),
LatLng(6.862258, 79.862325),
LatLng(6.863121, 79.863644),
LatLng(6.864538, 79.865039),
LatLng(6.865124, 79.864546),
LatLng(6.866451, 79.864667),
LatLng(6.867303, 79.86544),
LatLng(6.867899, 79.865826),
LatLng(6.867867, 79.866727),
LatLng(6.864884, 79.870333),
LatLng(6.861859, 79.873112),
LatLng(6.861593, 79.87499),
LatLng(6.860837, 79.876427),
];
}

if you are using goole_maps_flutter plugin, on ver.0.5.6, support for polylines have been added to GoogleMaps.
https://pub.dev/packages/google_maps_flutter#056
you can add it similar to how you add markers:
body:Container(
child: GoogleMap(
myLocationEnabled: true,
mapType: MapType.hybrid,
onMapCreated: (GoogleMapController controller){
mapController=controller;
},
initialCameraPosition: CameraPosition(
target: center,
zoom: 11.0
),
markers: markers,
polylines: polylines, // Set<Polyline>
),
),
check out the following example:
https://github.com/flutter/plugins/blob/master/packages/google_maps_flutter/example/lib/place_polyline.dart

Related

navigate to google map's location marker by clicking card widget in flutter app

I wanted to design a card when clicked it will navigate to a specified marker
I fetched my coordinates (markers) from cloud firestore. everything works perfectly. but when I tried to link my marker with card using pageview.builder it fails.
I already connected and fetch all the markers from firebase: firestore. the only problem I got is that I can't connect my markers.
maybe at the end of the code I used 'Future' to specify the movement of the camera wile navigating and I used it outside of pageview.builder.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
import 'package:permission/permission.dart';
class Metro extends StatefulWidget {
#override
_MetroState createState() => _MetroState();
}
String stations;
class _MetroState extends State<Metro> {
// GoogleMapController _controller;
// final CameraPosition _initialPosition = CameraPosition(target: LatLng(9.0131, 38.7240), zoom: 17.0);
LatLng _initialPosition = LatLng(9.0131, 38.7240);
GoogleMapController _controller;
Location _location= Location();
int prevPage;
PageController _pageController;
void _onMapCreated(GoogleMapController _cntrl){
_controller = _cntrl;
_location.onLocationChanged.listen((l) {
_controller.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(target: LatLng(l.latitude, l.longitude), zoom: 15)));
});
}
Map<MarkerId, Marker> markers = <MarkerId, Marker>{};
void initMarker(specify, specifyId) async {
var markerIdVal = specifyId;
final MarkerId markerId = MarkerId(markerIdVal);
final Marker marker = Marker(
markerId: markerId,
draggable: false,
position:
LatLng(specify['Location'].latitude, specify['Location'].longitude),
infoWindow: InfoWindow(title: specify['Name'], snippet: 'Station'),
);
setState(() {
markers[markerId] = marker;
},
);
_pageController = PageController(initialPage: 0, viewportFraction: 0.8)..addListener(_onScroll);
}
void _onScroll() {
if (_pageController.page.toInt() != prevPage) {
prevPage = _pageController.page.toInt();
moveCamera();
}
}
getMarkerData() async {
Firestore.instance.collection('route 1 markers').getDocuments().then((myMockDoc) {
if (myMockDoc.documents.isNotEmpty) {
for (int i = 0; i < myMockDoc.documents.length; i++) {
initMarker(myMockDoc.documents[i].data, myMockDoc.documents[i].documentID);
}
}
}
);
}
#override
void initState() { enter code here
getMarkerData();
super.initState();
}
#override
Widget build(BuildContext context) {
Set<Marker> getMarker() {
return <Marker>[
Marker(
markerId: MarkerId('Station'),
position: _initialPosition,
icon: BitmapDescriptor.defaultMarker,
infoWindow: InfoWindow(title: 'Home'))
].toSet();
}
return Scaffold(
// floatingActionButton: FloatingActionButton(
// onPressed: (){},
// backgroundColor: Colors.lightGreen,
// child: Icon(Icons.search),
// ),
body: Stack(
children: [
GoogleMap(
markers: Set<Marker>.of(markers.values),
mapType: MapType.normal,
initialCameraPosition: CameraPosition(target: _initialPosition, zoom: 25),
onMapCreated: _onMapCreated,
myLocationEnabled: true,
myLocationButtonEnabled: true,
mapToolbarEnabled: false,
),
Positioned(
bottom: 20.0,
child: Container(
height: 200,
width: MediaQuery.of(context).size.width,
child: StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('route 1 markers').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return new Text('Loading...');
default:
return PageView.builder( // Changes begin here
controller: _pageController,
scrollDirection: Axis.horizontal,
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
final document = snapshot.data.documents[index];
return AnimatedBuilder(
animation: _pageController,
builder: (BuildContext context, Widget widget){
double value = 1;
if (_pageController.position.haveDimensions) {
value = _pageController.page - index;
value = (1 - (value.abs() * 0.3) + 0.06).clamp(0.0, 1.0);
}
return Center(
child: SizedBox(
height: Curves.easeInOut.transform(value) * 125.0,
width: Curves.easeInOut.transform(value) * 350.0,
child: widget,
),
);
},
child: InkWell(
onTap: (){moveCamera();},
child: Stack(
children: [
Center(
child: Container(
margin: EdgeInsets.symmetric(
horizontal: 10.0,
vertical: 20.0
),
height: 125,
width: 270,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
boxShadow: [
BoxShadow(
color: Colors.black54,
offset: Offset(0.0, 4.0),
blurRadius: 10.0,
),
]),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color: Colors.white
),
child: Row(
children: [
Container(
height: 90,
width: 90,
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(10.0),
topLeft: Radius.circular(10.0)),
image: DecorationImage(
image: NetworkImage(
document['img']),
fit: BoxFit.cover))),
SizedBox(width: 5.0),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
document['Name'],
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold),
),
Positioned(
bottom: 5.0,
child: Text(
"Addis Ababa, Ethiopia",
style: TextStyle(
fontSize: 13.0,
fontWeight: FontWeight.w600),
),
),
Container(
width: 170,
child: Text(
document['Detail'],
style: TextStyle(
fontSize: 12.0,
fontWeight: FontWeight.w300),
),
),
],
)
],
),
),
),
)
],
),
),
);
}
);
}
},
),
))
],
),
);
}
Future<void> moveCamera() async{
_controller.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(
target: document[_pageController.page.toInt()].Location,
zoom: 14.0,
tilt: 45.0,
bearing: 45.0,
)));
}
}
SO I need your help, help me out please. I posted my code

Flutter: show Circularprogressindicator while build Googlemap

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.

GoogleMap in Drawer flutter

I would like to limit the size of the map to a part of the drawer and to show the current location marked on the map. This way it stays on the whole drawer and only shows the location when I press the location symbol...
Widget _buildDrawer(BuildContext context) {
return Drawer(
child: Flex(
direction: Axis.horizontal,
children: [
Expanded(
child:GoogleMap(
mapType: MapType.normal,
myLocationEnabled: true,
initialCameraPosition: _currentPosition,
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
))]));
}
...
currentPosition = CameraPosition(
bearing: 192.8334901395799,
target: LatLng(latitude, longitude),
tilt: 59.440717697143555,
zoom: 19.151926040649414);
Tried too: but is in full again
Drawer(
child: Container(
height: MediaQuery.of(context).size.height * 0.10,
width: MediaQuery.of(context).size.width * 0.10,
child: Row(
children: <Widget>[
Expanded(
flex: 70,
child: GoogleMap(
mapType: MapType.hybrid,
mapToolbarEnabled: false,
zoomControlsEnabled: false,
myLocationEnabled: true,
initialCameraPosition: _currentPosition,
onMapCreated: (GoogleMapController controller) async {
_controller.complete(controller);
},
),
)])))
child: Column(children: [GoogleMap()])
this way you can store multiple widgets within the draw without having the map take up the entire widget.
You have to options as far as styling the GoogleMap() widget
You can change the style within the google map widget
2)You can style the parent widget which holds the GooggleMap()
for column this would be => Column(mainaxisalignmen: mainaxisalignment.center etc.
column is not the only widget you have to use, any widget that takes children is a good choice for being the child of the drawer

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.

Remove bottom right button from google maps flutter

There is a button in the bottom right of the google maps API google maps widget. I never added this button myself. How do I remove it?
edit:
here is my code
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("TravelBuddy"),
),
body: Stack(
children: <Widget>[
GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition:
CameraPosition(
target: _center,
zoom: 11.0,
),
mapType: _currentMapType,
markers: _markers,
onCameraMove: _onCameraMove,
),
Padding(
padding: EdgeInsets.all(16.0),
child: Align(
alignment: Alignment.topRight,
child: Column(
children: <Widget>[
button(_onMapTypeButtonPressed, Icons.map),
SizedBox(height: 16.0),
button(_onAddMarkerButtonPressed, Icons.add_location),
SizedBox(height: 16.0),
button(_goToPosition1, Icons.location_searching),
],),),),],),);}
Thanks for the code.
Try putting an option "my LocationButtonEnabled" in GoogleMap() widget
GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition:
CameraPosition(
target: _center,
zoom: 11.0,
),
mapType: _currentMapType,
markers: _markers,
onCameraMove: _onCameraMove,
myLocationButtonEnabled: false,
options: GoogleMapOptions(
myLocationEnabled:true
//there is a lot more options you can add here
)
),
I had a similar problem. Adding 'zoomControlsEnabled: false,' in the GoogleMap() widget worked for me.