How to add marker in the google map using flutter? - google-maps

I am creating a nearby flutter app which shows restaurant around your location. i have found the nearby location but unable to add markers on the nearby coordinates.I want to know how to add markers to my location using google API and how to load the location from the list to my map.
void getData() async {
http.Response response = await http.get(
'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=1500&type=restaurant&key=API_KEY');
if (response.statusCode == 200) {
String data = response.body;
var decodedData = jsonDecode(data);
print(decodedData);
List<String> names = [];
List<double> lat = [];
List<double> lng = [];
for (var i = 0; i < 10; i++) {
names.add(decodedData['results'][i]['name']);
lat.add(decodedData['results'][i]['geometry']['location']['lat']);
lng.add(decodedData['results'][i]['geometry']['location']['lng']);
}
print(names);
print(lat);
print(lng);
}
}
Expanded(
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(-33.8670522, 151.1957362),
zoom: 14.4746,
),
markers: Set<Marker>.of(markers.values),
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
),
),
),

Make sure you add your API_KEY. A working example of your requirement follows
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
LatLng latlng = LatLng(
-33.8670522,
151.1957362,
);
Iterable markers = [];
#override
void initState() {
super.initState();
getData();
}
getData() async {
try {
final response =
await http.get('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=1500&type=restaurant&key=API_KEY');
final int statusCode = response.statusCode;
if (statusCode == 201 || statusCode == 200) {
Map responseBody = json.decode(response.body);
List results = responseBody["results"];
Iterable _markers = Iterable.generate(10, (index) {
Map result = results[index];
Map location = result["geometry"]["location"];
LatLng latLngMarker = LatLng(location["lat"], location["lng"]);
return Marker(markerId: MarkerId("marker$index"),position: latLngMarker);
});
setState(() {
markers = _markers;
});
} else {
throw Exception('Error');
}
} catch(e) {
print(e.toString());
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: GoogleMap(
markers: Set.from(
markers,
),
initialCameraPosition: CameraPosition(target: latlng, zoom: 15.0),
mapType: MapType.hybrid,
onMapCreated: (GoogleMapController controller) {},
),
);
}
}

In the end you have to structure it yourself but it should look something like this
final Set<Marker> _markers = {};
setState(() {
// add marker on the position
_markers.add(Marker(
// This marker id can be anything that uniquely identifies each marker.
markerId: MarkerId(_lastMapPosition.toString()),
position: _lastMapPosition,
infoWindow: InfoWindow(
// title is the address
title: address.addressLine,
// snippet are the coordinates of the position
snippet: 'Lat: ${address.coordinates.latitude}, Lng: ${address
.coordinates.longitude}',
),
icon: BitmapDescriptor.defaultMarker,
));
}

Iterable markers = [];
// in GoogleMap use like this
GoogleMap(...
markers: Set.from(markers),
),
// in function or where you want
Iterable _markers = Iterable.generate(list.length, (index) {
return Marker(
markerId: MarkerId("marker$index"),
position: list[index].position);
});
setState(() {
markers = _markers;
});

Related

Flutter How Can I Get Markers from JSON API and show on Google Map

I make a simple app get data marker from JSON API and draw them on Google Map.
I have get marker information from the API (URL) and added it to the list allMarkers.
But when I run my app, Map is not working and got this error:
type 'List<dynamic>' is not a subtype of type 'String'
This is my full Home.dart code
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:google_maps_flutter/google_maps_flutter.dart';
class Home extends StatefulWidget {
#override
_Home2State createState() => _HomeState();
}
class _HomeState extends State<Home> {
Future _future;
Future loadString() async {
var url = "http://10.0.2.2/GoApp/locations.php";
var response = await http.get(url);
final dynamic responsebody = jsonDecode(response.body);
print(responsebody);
return responsebody;
}
List<Marker> allMarkers = [];
GoogleMapController _controller;
#override
void initState() {
// TODO: implement initState
super.initState();
_future = loadString();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(children: [
Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: FutureBuilder(
future: _future,
builder: (context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
List<dynamic> parsedJson = jsonDecode(snapshot.data);
allMarkers = parsedJson.map((i) {
return Marker(
markerId: MarkerId(i['loc_id']),
position: LatLng(i['loc_x'], i['loc_y']),
onTap: () {},
);
}).toList();
return GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(40.7128, -74.0060), zoom: 1.0),
markers: Set.from(allMarkers),
onMapCreated: mapCreated,
mapType: MapType.normal,
tiltGesturesEnabled: true,
compassEnabled: true,
rotateGesturesEnabled: true,
myLocationEnabled: true,
);
},
),
),
]),
);
}
void mapCreated(controller) {
setState(() {
_controller = controller;
});
}
}
My json data from URL:
[
{
"loc_id": "8D5D-4CD323560F59",
"loc_x": 40.7128,
"loc_y": -74.0060
},
{
"loc_id": "E3E0D2C5-CB82",
"loc_x": 41.7128,
"loc_y": -75.0060
}
]
How Can Resolved This Issuse?

My stream crashes after obtaining latitude and longitude twice, and doesn't follow my current position. What is causing this?

After two geolocation updates, it crashes and doesn't follow me in the map:
StreamSubscription subscription;
super.initState();
subscription = getPositionStream(desiredAccuracy: LocationAccuracy.high, distanceFilter: 10).listen(
(Position position) async {
getLocation();
centerScreen(position);
print(position == null ? 'Unknown' : position.latitude.toString() + ', ' + position.longitude.toString());
});
}
just to be safe, i tried adding: subscription.resume() to my _onMapCreated (flutter google maps). No impact...
Here's my getLocation:
Future getLocation() async {
Position position =
await getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
lat = position.latitude;
lng = position.longitude;
setState(() {});
}
and my center screen function:
Future<void> centerScreen(Position position) async {
final GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(
target: LatLng(position.latitude, position.longitude),
zoom: _currentZoom)));
}
This is with the latest release of flutter geolocator and flutter google maps.
I've been trying to figure this out for two days... I would really appreciate your help. Thank you in advance.
Took it out of my init state. Passed it to getLocation like so:
Future getLocation() async {
subscription = getPositionStream(desiredAccuracy: LocationAccuracy.high, distanceFilter: 10).listen(
(Position position) async {
final GoogleMapController controller = await _controller.future;
// final GoogleMapController currentZoom = await _controller.zoom;
controller.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(
target: LatLng(position.latitude, position.longitude),
zoom: _currentZoom)));
});
works well.
GoogleMapFlutter with Geolocator
// GoogleMapFlutter with Geolocator
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';
class Map extends StatefulWidget {
#override
_MapState createState() => _MapState();
}
class _MapState extends State<Map> {
bool mapToggle = false;
var currentLocation;
#override
//initiate position
void initState() {
super.initState();
//Geolocation
Geolocator.getCurrentPosition().then((currloc) {
setState(() {
currentLocation = currloc;
mapToggle = true;
});
});
}
//Location Marker
Set<Marker> _createMarker() {
return <Marker>[
Marker(
markerId: MarkerId("currentLocation"),
position: LatLng(currentLocation.latitude, currentLocation.longitude),
icon: BitmapDescriptor.defaultMarker,
infoWindow: InfoWindow(title: "Your Location"),
)
].toSet();
}
#override
Widget build(BuildContext context) {
return Stack(
children: [
mapToggle
//Google Map flutter
? GoogleMap(
mapType: MapType.normal,
markers: _createMarker(),
initialCameraPosition: CameraPosition(
target: LatLng(
currentLocation.latitude, currentLocation.longitude),
zoom: 15.0))
//Loading
: Center(
child: Text(
'Loading.. Please wait..',
style: TextStyle(fontSize: 20.0),
)),
],
);
}
}

my flutter asset image is not being used as my marker icon for google maps

I have created a customised image to use as my marker icon for one of my markers on google maps on my flutter app. Unfortunately, this is not working as planned and the default icon is being displayed instead. Can anybody spot the eroor? I certainly can't. As a side note, nothing in my if statements is being printed in the console. An issue for another day?
This is the code I used to get up my marker:
var map;
var rmarker;
final restaurantmarker = BitmapDescriptor.fromAssetImage(
ImageConfiguration(), 'assets/images/yellow_MarkerR.png')
.then((value) => rmarker = value);
final mapp = location.getLocation().then((value) => map = value);
final _markers = [
Marker(
markerId: MarkerId("my_location"),
position: LatLng(41.16599, -110.75792),
infoWindow: InfoWindow(title: "YOUR HOME"),
),
Marker(
markerId: MarkerId("RESTAURANT"),
icon: rmarker,
position: LatLng(40.16599, -110.75792),
infoWindow: InfoWindow(title: "Restaurant"))
];
final setmarkers = _markers.toSet();
class NearbyScreen extends StatelessWidget {
void initState() {
startService();
}
#override
//LocationHelper.mapviewpointer(latitude: )
Widget build(BuildContext context) {
return /* !_serviceEnabled ? Center(child:Text("Page cannot be viewed"),) :
map == null
? Center(
child: Text("Null response"),
)
:*/
GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(41.16599,
-110.75792 /*map.latitude, map.longitude
double.parse(coordinates[0]), double.parse(coordinates[1]) */
)),
//minMaxZoomPreference: MinMaxZoomPreference(10, 20),
zoomControlsEnabled: true,
markers: setmarkers,
);
}
}
And this is the full code:
Future<bool> assignService(Location loc) async {
bool servicestatus = await loc.serviceEnabled();
print("Service status $servicestatus");
return servicestatus;
}
Future<PermissionStatus> assignPermission(Location loc) async {
var hasPermission = await loc.hasPermission();
print("Permission status $hasPermission");
return hasPermission;
}
Location location = Location();
var _serviceEnabled;
var _serve = assignService(location).then((value) => _serviceEnabled = value);
//var _permissionGranted = assignPermission(location);
var _permissionGranted;
var _permi =
assignPermission(location).then((value) => _permissionGranted = value);
void startService() {
if (!_serviceEnabled) {
_serviceEnabled = assignService(location);
print("service disabled");
if (!_serviceEnabled) {
return;
}
}
if (_permissionGranted == PermissionStatus.denied) {
_permissionGranted = assignPermission(location);
print("permission denied");
if (_permissionGranted != PermissionStatus.granted) {
return;
}
}
}
var map;
var rmarker;
final restaurantmarker = BitmapDescriptor.fromAssetImage(
ImageConfiguration(), 'assets/images/yellow_MarkerR.png')
.then((value) => rmarker = value);
final mapp = location.getLocation().then((value) => map = value);
final _markers = [
Marker(
markerId: MarkerId("my_location"),
position: LatLng(41.16599, -110.75792),
infoWindow: InfoWindow(title: "YOUR HOME"),
),
Marker(
markerId: MarkerId("RESTAURANT"),
icon: rmarker,
position: LatLng(40.16599, -110.75792),
infoWindow: InfoWindow(title: "Restaurant"))
];
final setmarkers = _markers.toSet();
class NearbyScreen extends StatelessWidget {
void initState() {
startService();
}
#override
//LocationHelper.mapviewpointer(latitude: )
Widget build(BuildContext context) {
return /* !_serviceEnabled ? Center(child:Text("Page cannot be viewed"),) :
map == null
? Center(
child: Text("Null response"),
)
:*/
GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(41.16599,
-110.75792 /*map.latitude, map.longitude
double.parse(coordinates[0]), double.parse(coordinates[1]) */
)),
//minMaxZoomPreference: MinMaxZoomPreference(10, 20),
zoomControlsEnabled: true,
markers: setmarkers,
);
}
}
I am also getting an error in my terminal that says: E/Parcel (22617): Reading a NULL string not supported here.
E/Parcel (22617): Reading a NULL string not supported here.
Looks like you are not retrieving the marker icon on your code properly as you only define it as restaurantmarker. Here is how you can resolve this:
First, you need to make sure that you have define your icon on your pubspec.yaml under Flutter: section:
Flutter:
assets:
- assets/images/yellow_MarkerR.png
Then, you will need to call the BitmapDescriptor.fromAssetImage inside initState() to get the icon before the map loads:
void initState() {
BitmapDescriptor.fromAssetImage(
ImageConfiguration(), 'assets/images/yellow_MarkerR.png')
.then((value) => rmarker = value);
}
There are many issues with your code and I just refactored the important part of your code for maps logic.
But the important issue is that you are not insuring the initialization of restaurantMarker. I added a check for that here which isSetupReady;
First, make sure you have added icon assets assets/images/yellow_MarkerR.png into your pubsepc.yaml file.
import 'package:flutter/material.dart';
class NearbyScreen extends StatefulWidget {
#override
_NearbyScreenState createState() => _NearbyScreenState();
}
class _NearbyScreenState extends State<NearbyScreen> {
var _markers;
var setmarkers;
var restaurantMarker;
bool isSetupReady = false;
#override
void initState() {
doSetup();
super.initState();
}
doSetup() async {
restaurantMarker = await BitmapDescriptor.fromAssetImage(
ImageConfiguration(), 'assets/images/yellow_MarkerR.png');
_markers = [
Marker(
markerId: MarkerId("my_location"),
position: LatLng(41.16599, -110.75792),
infoWindow: InfoWindow(title: "YOUR HOME"),
),
Marker(
markerId: MarkerId("RESTAURANT"),
icon: rmarker,
position: LatLng(40.16599, -110.75792),
infoWindow: InfoWindow(title: "Restaurant"))
];
setmarkers = _markers.toSet();
setState(() {
isSetupReady = true;
});
}
#override
//LocationHelper.mapviewpointer(latitude: )
Widget build(BuildContext context) {
return /* !_serviceEnabled ? Center(child:Text("Page cannot be viewed"),) :
map == null
? Center(
child: Text("Null response"),
)
:*/
isSetupReady
? GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(41.16599,
-110.75792 /*map.latitude, map.longitude
double.parse(coordinates[0]), double.parse(coordinates[1]) */
)),
//minMaxZoomPreference: MinMaxZoomPreference(10, 20),
zoomControlsEnabled: true,
markers: setmarkers,
)
: Center(child: Text('Loading Maps...'));
}
}

Flutter Google Maps not determining current location of device

I'm using Flutter's Geolocator and Google Maps packages to determine a device's location. I utilize the Circular Progress Bar to wait for the current location to be determined. Once determined, Google Maps loads with the device's location identified.
When the application loads, the circular progress bar is displayed but the map is not loaded despite the notification being displayed and accepted to use location services; the app hangs on the circular progress bar. I don't believe this to be an API issue as I have had success loading the map with coordinates specified in InitialCameraPosition.
Is the device's location not being determined which is the cause for the map to not load with the location indicated?
I've tried running the app on both Android emulator and a physical device without success.
Android Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="smartkart.app.com.coffee">
<!-- io.flutter.app.FlutterApplication is an android.app.Application
that
calls FlutterMain.startInitialization(this); in its onCreate
method.
In most cases you can leave this as-is, but you if you want to
provide
additional functionality it is fine to subclass or reimplement
FlutterApplication and put your custom class here. -->
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:name="io.flutter.app.FlutterApplication"
android:label="coffee"
android:icon="#mipmap/ic_launcher">
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="API KEY HERE"/>
<activity../>
Maps Screen
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';
class FirstScreen extends StatefulWidget {
const FirstScreen({Key key}) : super(key: key);
#override
State<FirstScreen> createState() => _FirstScreen();
}
class _FirstScreen extends State<FirstScreen> {
GoogleMapController mapController;
var currentLocation;
#override
void initState(){
super.initState();
Geolocator().getCurrentPosition().then((currloc){
currentLocation = currloc;
});
}
#override
Widget build(BuildContext context) {
return currentLocation == null ? Container(
alignment: Alignment.center,
child: Center(
child: CircularProgressIndicator(),
),
):
Stack(
children: <Widget>[
GoogleMap(
initialCameraPosition:
CameraPosition(target: LatLng(currentLocation.latitude,
currentLocation.longitude), zoom: 10),
onMapCreated: _onMapCreated,
myLocationEnabled: true,
mapType: MapType.normal,
),
],
);
}
void _onMapCreated(GoogleMapController controller) {
setState(() {
mapController = controller;
});
}
}
I expect the notification to use location services to appear while the circular progress bar is displayed. Once the location is determined, the InitialCameraPosition displays the device's location on the map.
Try the following code as a solution. You can modify the map widget to your use case:
import 'package:flutter/cupertino.dart';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
class Map extends StatefulWidget {
#override
_MapState createState() => _MapState();
}
class _MapState extends State<Map> {
Completer<GoogleMapController> controller1;
//static LatLng _center = LatLng(-15.4630239974464, 28.363397732282127);
static LatLng _initialPosition;
final Set<Marker> _markers = {};
static LatLng _lastMapPosition = _initialPosition;
#override
void initState() {
super.initState();
_getUserLocation();
}
void _getUserLocation() async {
Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
List<Placemark> placemark = await Geolocator().placemarkFromCoordinates(position.latitude, position.longitude);
setState(() {
_initialPosition = LatLng(position.latitude, position.longitude);
print('${placemark[0].name}');
});
}
_onMapCreated(GoogleMapController controller) {
setState(() {
controller1.complete(controller);
});
}
MapType _currentMapType = MapType.normal;
void _onMapTypeButtonPressed() {
setState(() {
_currentMapType = _currentMapType == MapType.normal
? MapType.satellite
: MapType.normal;
});
}
_onCameraMove(CameraPosition position) {
_lastMapPosition = position.target;
}
_onAddMarkerButtonPressed() {
setState(() {
_markers.add(
Marker(
markerId: MarkerId(_lastMapPosition.toString()),
position: _lastMapPosition,
infoWindow: InfoWindow(
title: "Pizza Parlour",
snippet: "This is a snippet",
onTap: (){
}
),
onTap: (){
},
icon: BitmapDescriptor.defaultMarker));
});
}
Widget mapButton(Function function, Icon icon, Color color) {
return RawMaterialButton(
onPressed: function,
child: icon,
shape: new CircleBorder(),
elevation: 2.0,
fillColor: color,
padding: const EdgeInsets.all(7.0),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: _initialPosition == null ? Container(child: Center(child:Text('loading map..', style: TextStyle(fontFamily: 'Avenir-Medium', color: Colors.grey[400]),),),) : Container(
child: Stack(children: <Widget>[
GoogleMap(
markers: _markers,
mapType: _currentMapType,
initialCameraPosition: CameraPosition(
target: _initialPosition,
zoom: 14.4746,
),
onMapCreated: _onMapCreated,
zoomGesturesEnabled: true,
onCameraMove: _onCameraMove,
myLocationEnabled: true,
compassEnabled: true,
myLocationButtonEnabled: false,
),
Align(
alignment: Alignment.topRight,
child: Container(
margin: EdgeInsets.fromLTRB(0.0, 50.0, 0.0, 0.0),
child: Column(
children: <Widget>[
mapButton(_onAddMarkerButtonPressed,
Icon(
Icons.add_location
), Colors.blue),
mapButton(
_onMapTypeButtonPressed,
Icon(
IconData(0xf473,
fontFamily: CupertinoIcons.iconFont,
fontPackage: CupertinoIcons.iconFontPackage),
),
Colors.green),
],
)),
)
]),
),
);
}
}
You seem to be missing setState in your initState.
It should look like this:
#override
void initState(){
super.initState();
Geolocator().getCurrentPosition().then((currloc){
setState((){
currentLocation = currloc;
});
});
}
Use GeoLocator package with google_maps_flutter
Sample Code:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';
class MapScreen extends StatefulWidget {
#override
State<MapScreen> createState() => MapScreenState();
}
class MapScreenState extends State<MapScreen> {
LatLng initPosition = LatLng(0, 0); //initial Position cannot assign null values
LatLng currentLatLng= LatLng(0.0, 0.0); //initial currentPosition values cannot assign null values
LocationPermission permission = LocationPermission.denied; //initial permission status
Completer<GoogleMapController> _controller = Completer();
#override
void initState() {
super.initState();
getCurrentLocation();
checkPermission();
}
//checkPersion before initialize the map
void checkPermission() async{
permission = await Geolocator.checkPermission();
}
// get current location
void getCurrentLocation() async{
await Geolocator.getCurrentPosition().then((currLocation) {
setState(() {
currentLatLng =
new LatLng(currLocation.latitude, currLocation.longitude);
});
});
}
//call this onPress floating action button
void _currentLocation() async {
final GoogleMapController controller = await _controller.future;
getCurrentLocation();
controller.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(
bearing: 0,
target: currentLatLng,
zoom: 18.0,
),
));
}
//Check permission status and currentPosition before render the map
bool checkReady(LatLng? x, LocationPermission? y) {
if (x == initPosition || y == LocationPermission.denied || y == LocationPermission.deniedForever) {
return true;
} else {
return false;
}
}
#override
Widget build(BuildContext context) {
print(permission);
print("Current Location --------> " +
currentLatLng.latitude.toString() +
" " +
currentLatLng.longitude.toString());
return MaterialApp(
//remove debug banner on top right corner
debugShowCheckedModeBanner: false,
home: new Scaffold(
//ternary operator use for conditional rendering
body: checkReady(currentLatLng, permission)
? Center(child: CircularProgressIndicator())
//Stack : place floating action button on top of the map
: Stack(children: [
GoogleMap(
myLocationEnabled: true,
myLocationButtonEnabled: false,
zoomControlsEnabled: false,
mapType: MapType.normal,
initialCameraPosition: CameraPosition(target: currentLatLng),
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
),
//Positioned : use to place button bottom right corner
Positioned(
bottom: 0,
right: 0,
child: Container(
margin: EdgeInsets.all(15),
child: FloatingActionButton(
onPressed: _currentLocation,
child: Icon(Icons.location_on)),
),
),
]),
),
);
}
}

How to print several markers google map api 0.5.7 Flutter

I am trying to use google map api last version (0.5.7) but on my map there is only one marker that is printed but there are many markes on the database and it was working well before I tried to put the last version. Does someone know how to print many markers ? I put arrow where the markers are used.
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
import 'package:geoflutterfire/geoflutterfire.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:rxdart/rxdart.dart';
import 'dart:async';
import 'package:intl/intl.dart';
import 'customs_icons_icons.dart';
import 'Dialogs.dart';
import 'Metro.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: FireMap(),
));
}
}
class FireMap extends StatefulWidget {
State createState() => FireMapState();
}
class FireMapState extends State<FireMap> {
GoogleMapController mapController;
Location location = new Location();
Dialogs dialogs = new Dialogs();
Firestore firestore = Firestore.instance;
Geoflutterfire geo = Geoflutterfire();
BehaviorSubject<double> radius = BehaviorSubject(seedValue: 100.0);
Stream<dynamic> query;
StreamSubscription subscription;`enter code here`
Map<MarkerId, Marker> markers = <MarkerId, Marker>{};
MarkerId selectedMarker;
int _markerIdCounter = 1;
build(context) {
return Stack(children: [
GoogleMap(
initialCameraPosition:
CameraPosition(target: LatLng(45.758077, 4.833316), zoom: 15),
onMapCreated: _onMapCreated,
myLocationEnabled: true,
mapType: MapType.normal,
compassEnabled: true,
markers: Set<Marker>.of(markers.values),<---
),
Positioned(
bottom: 20,
right: 20,
child: Container(
height: 80.0,
width: 80.0,
child: FittedBox(
child: FloatingActionButton(
child: Icon(CustomsIcons.ticket, color: Colors.black),
backgroundColor: Colors.pink[200],
onPressed: () => dialogs.information(
context, 'Confirmer ?', 'description', addGeoPoint),
),
),
),
),
]);
}
_onMapCreated(GoogleMapController controller) {
_startQuery();
setState(
() {
mapController = controller;
},
);
}
void _updateMarkers(List<DocumentSnapshot> documentList) { <---
final String markerIdVal = 'marker_id_$_markerIdCounter';
_markerIdCounter++;
final MarkerId markerId = MarkerId(markerIdVal);
print(documentList);
markers.clear();
documentList.forEach(
(DocumentSnapshot document) {
GeoPoint pos = document.data['position']['geopoint'];
var marker = Marker(
markerId: markerId,
position: LatLng(pos.latitude, pos.longitude),
icon: BitmapDescriptor.fromAsset('assets/ticket_point.png'),
infoWindow:
InfoWindow(title: 'Ici à :', snippet: document.data['time']));
setState(() {
markers[markerId] = marker;
});
},
);
}
It works ! I just moved markerIDcounter in "(DocumentSnapshot document)" and all the markers appears
I do it like this way
class _MapActivityState extends State<MapActivity> {
GoogleMapController _controller;
static LatLng _center = LatLng(0.0, 0.0);
Position currentLocation;
Set<Marker> _markers = {};
void _onMapCreated(GoogleMapController controller) {
setState(() {
_controller = controller;
});
}
#override
void initState() {
super.initState();
setState(() {
getUserLocation();
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomPadding: false,
appBar: AppBar(
title: Text("Home"),
),
body: Stack(
children: <Widget>[
GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(target: _center, zoom: 15),
markers: _markers,
),
],
),
);
}
getUserLocation() async {
currentLocation = await locateUser();
setState(() {
for (int i = 0; i < myresponse.data.length; i++) {
_markers.add(Marker(
markerId: MarkerId(myresponse[i].userId),
position: LatLng(double.parse(myresponse[i].latitude),
double.parse(myresponse[i].longitude)),
icon: myresponse[i].capacity.contains("7.2")
? BitmapDescriptor.fromAsset(
'assets/charger_location.png',
)
: BitmapDescriptor.fromAsset(
'assets/marker_green.png',
),
infoWindow: InfoWindow(
title: myresponse[i].stationName,
snippet: myresponse[i].contactPerson,
onTap: () => _onTap(myresponse[i]))));
}
});
}
}