want to find a center of 2 points and fit a map.
I want to fit for all screen when I view on map.
I draw route ready but it fit to 1 point only. please help me.
this class is for map view for a flutter.
I try to find plugin and solution more day but still not found.
GoogleMap(
mapType: MapType.normal,
markers: _markers,
// cameraTargetBounds: CameraTargetBounds(new LatLngBounds(
// northeast: LatLng(latFrom, logFrom),
// southwest: LatLng(latTo, logTo),
// )),
// minMaxZoomPreference: MinMaxZoomPreference(1, 15),
mapToolbarEnabled: true,
scrollGesturesEnabled: true,
zoomGesturesEnabled: true,
trafficEnabled: true,
compassEnabled: true,
indoorViewEnabled: true,
rotateGesturesEnabled: true,
tiltGesturesEnabled: true,
myLocationButtonEnabled: true,
myLocationEnabled: true,
polylines: _polyline,
// padding: EdgeInsets.all(20),
initialCameraPosition:
CameraPosition(
target: LatLng(latFrom, logFrom),
zoom: 10,
),
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
})
void _setMapFitToTour(Set<Polyline> p) {
double minLat = p.first.points.first.latitude;
double minLong = p.first.points.first.longitude;
double maxLat = p.first.points.first.latitude;
double maxLong = p.first.points.first.longitude;
p.forEach((poly) {
poly.points.forEach((point) {
if(point.latitude < minLat) minLat = point.latitude;
if(point.latitude > maxLat) maxLat = point.latitude;
if(point.longitude < minLong) minLong = point.longitude;
if(point.longitude > maxLong) maxLong = point.longitude;
});
});
mapController.moveCamera(CameraUpdate.newLatLngBounds(LatLngBounds(
southwest: LatLng(minLat, minLong),
northeast: LatLng(maxLat,maxLong)
), 20));
}
google_maps_flutter: ^0.5.30
flutter_polyline_points: ^0.2.2
Make sure you have used .then() function because setPolyline() is the async function and has the await keyword.
Use these dependencies
class ShowMap extends StatefulWidget {
ShowMap({Key key}) : super(key: key);
#override
_ShowMapState createState() => _ShowMapState();
}
class _ShowMapState extends State<ShowMap> {
GoogleMapController _googleMapController;
Set<Polyline> _polylines = {};
List<LatLng> polylineCoordinates = [];
PolylinePoints polylinePoints = PolylinePoints();
String googleAPIKey = "YOUR_API_KEY_HERE";
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: ColorUtils.bluePrimary,
appBar: AppBar(
// automaticallyImplyLeading: false,
backgroundColor: ColorUtils.greenPrimary,
title: Center(
child: Column(
children: [
Text(
'Delivery Accepted! ',
style: TextStyle(fontSize: 18.0, letterSpacing: -0.3333),
),
],
),
),
),
body: Column(
children: [
Expanded(
flex: 5,
child: Center(
child: Container(
margin: EdgeInsets.only(top: 10),
decoration: BoxDecoration(
// color: Colors.white,
),
width: MediaQuery.of(context).size.width - 10,
height: MediaQuery.of(context).size.height * 0.5,
child: GoogleMap(
cameraTargetBounds: CameraTargetBounds.unbounded,
initialCameraPosition: _initialPosition,
onMapCreated: _onMapCreated,
tiltGesturesEnabled: true,
scrollGesturesEnabled: true,
zoomGesturesEnabled: true,
// trafficEnabled: true,
polylines: _polylines),
),
),
),
),
],
),
);
}
static final CameraPosition _initialPosition = CameraPosition(
// bearing: 192.8334901395799,
target: LatLng(31.5204, 74.3587),
zoom: 12);
void _onMapCreated(GoogleMapController controller) async {
setState(() {
_googleMapController = controller;
setPolylines().then((_) => _setMapFitToTour(_polylines));
});
}
void _setMapFitToTour(Set<Polyline> p) {
double minLat = p.first.points.first.latitude;
double minLong = p.first.points.first.longitude;
double maxLat = p.first.points.first.latitude;
double maxLong = p.first.points.first.longitude;
p.forEach((poly) {
poly.points.forEach((point) {
if (point.latitude < minLat) minLat = point.latitude;
if (point.latitude > maxLat) maxLat = point.latitude;
if (point.longitude < minLong) minLong = point.longitude;
if (point.longitude > maxLong) maxLong = point.longitude;
});
});
_googleMapController.animateCamera(CameraUpdate.newLatLngBounds(
LatLngBounds(
southwest: LatLng(minLat, minLong),
northeast: LatLng(maxLat, maxLong)),
20));
}
setPolylines() async {
PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
googleAPIKey,
PointLatLng(31.5204, 74.3587),
PointLatLng(31.4504, 74.1350),
);
if (result.points.isNotEmpty) {
result.points.forEach((PointLatLng point) {
polylineCoordinates.add(LatLng(point.latitude, point.longitude));
});
} else {
print("--address not found ---");
}
setState(() {
Polyline polyline = Polyline(
polylineId: PolylineId("poly"),
color: Color.fromARGB(255, 40, 122, 198),
width: 5,
points: polylineCoordinates);
_polylines.add(polyline);
});
}
}
Today I got the same problem and I stumbled upon your question. Looking through the answers while implementing i found a simpler approach.
The LatLangBounds class has a method in there called .fromPoint(List<LatLng> points) which takes a list of points and returns the bounds.
I used this with the MapController class and it worked perfectly showing the bounds on the map. Per my understanding of GoogleMapController it should work.
mapController.fitBounds(LatLngBounds.fromPoints(list_of_points));
Ideally this should be what the google map equivalent should be
googleMapController.moveCamera(
CameraUpdate.newLatLngBounds(
LatLngBounds.fromPoints(list_of_points)
),zoomIndex)
);
The .fromPoints(List<LatLng> points) method does what everyone has virtually implemented. Hopefully this helps anyone who needs it.
Today I got the same problem and I stumbled upon your question. And I found two links that can help.
https://medium.com/flutter-community/drawing-route-lines-on-google-maps-between-two-locations-in-flutter-4d351733ccbe
https://stackoverflow.com/a/55990256/1537413
after combine these two links, I get perfect solution.
Here you go.
import 'dart:async';
import 'package:app/env.dart';
import 'package:flutter/material.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
class RoutePage extends StatefulWidget {
#override
_RoutePageState createState() => _RoutePageState();
}
class _RoutePageState extends State<RoutePage> {
Completer<GoogleMapController> _controller = Completer();
GoogleMapController mapController;
final Set<Marker> _markers = {};
Set<Polyline> _polylines = {};
List<LatLng> polylineCoordinates = [];
PolylinePoints polylinePoints = PolylinePoints();
String googleAPIKey = GOOGLE_MAPS_API_KEY;
static LatLng sourceLocation = LatLng(42.7477863, -71.1699932);
static LatLng destLocation = LatLng(42.6871386, -71.2143403);
void _onMapCreated(GoogleMapController controller) async {
mapController = controller;
_controller.complete(controller);
LatLng temp;
if (sourceLocation.latitude > destLocation.latitude) {
temp = sourceLocation;
sourceLocation = destLocation;
destLocation = temp;
}
LatLngBounds bound =
LatLngBounds(southwest: sourceLocation, northeast: destLocation);
BitmapDescriptor sourceIcon = await BitmapDescriptor.fromAssetImage(
ImageConfiguration(devicePixelRatio: 2.5), 'assets/driving_pin.png');
BitmapDescriptor destinationIcon = await BitmapDescriptor.fromAssetImage(
ImageConfiguration(devicePixelRatio: 2.5),
'assets/destination_map_marker.png');
setState(() {
_markers.clear();
addMarker(sourceLocation, "Madrid", "5 Star Rating", icon: sourceIcon);
addMarker(destLocation, "Barcelona", "7 Star Rating",
icon: destinationIcon);
});
CameraUpdate u2 = CameraUpdate.newLatLngBounds(bound, 50);
this.mapController.animateCamera(u2).then((void v) {
check(u2, this.mapController);
});
}
void addMarker(LatLng mLatLng, String mTitle, String mDescription,
{BitmapDescriptor icon}) {
_markers.add(Marker(
markerId: MarkerId(
(mTitle + "_" + _markers.length.toString()).toString()), //must unique
position: mLatLng,
infoWindow: InfoWindow(
title: mTitle,
snippet: mDescription,
),
icon: icon,
));
}
void check(CameraUpdate u, GoogleMapController c) async {
c.animateCamera(u);
mapController.animateCamera(u);
LatLngBounds l1 = await c.getVisibleRegion();
LatLngBounds l2 = await c.getVisibleRegion();
print(l1.toString());
print(l2.toString());
if (l1.southwest.latitude == -90 || l2.southwest.latitude == -90)
check(u, c);
else {
await setPolylines();
}
}
void _onCameraMove(CameraPosition position) {}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Maps Sample App'),
backgroundColor: Colors.green[700],
),
body: GoogleMap(
myLocationEnabled: true,
compassEnabled: true,
tiltGesturesEnabled: false,
markers: _markers,
polylines: _polylines,
mapType: MapType.normal,
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(
target: sourceLocation,
zoom: 13.0,
),
onCameraMove: _onCameraMove,
),
),
);
}
setPolylines() async {
List<PointLatLng> result = await polylinePoints?.getRouteBetweenCoordinates(
googleAPIKey,
sourceLocation.latitude,
sourceLocation.longitude,
destLocation.latitude,
destLocation.longitude);
if (result.isNotEmpty) {
result.forEach((PointLatLng point) {
polylineCoordinates.add(LatLng(point.latitude, point.longitude));
});
}
setState(() {
Polyline polyline = Polyline(
polylineId: PolylineId("poly"),
color: Color.fromARGB(255, 40, 122, 198),
points: polylineCoordinates);
_polylines.add(polyline);
});
}
}
Related
I am using Flutter and the Google Maps API.
I have managed to have a custom marker that is displayed when the map opens.
Is there a way to have multiple different custom markers Images at the same time on the same map?
I can't find a way to do that.
Any ideas or links are welcomed :)
class Neighborhood extends StatefulWidget {
const Neighborhood({Key key}) : super(key: key);
#override
_NeighborhoodState createState() => _NeighborhoodState();
}
class _NeighborhoodState extends State<Neighborhood> {
Location _location = Location();
GoogleMapController _controller;
List<Marker> allMarkers = [];
PageController _pageController;
int prevPage;
int bottomSelectedIndex = 0;
//initialising the custom pinIcon
BitmapDescriptor pinIcon;
#override
void initState() {
super.initState();
//calling the the function that will await the pinIcon and have it ready with initState();
setCustomMapPin();
_pageController = PageController(initialPage: 1, viewportFraction: 0.8)
..addListener(_onScroll);
}
void _onScroll() {...
_myPlacesList(index) {...
Then I created the Google Map
child: GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(40.505757, 22.846576),
zoom: 12.0,
),
onMapCreated: mapCreated,
myLocationEnabled: true,
myLocationButtonEnabled: true,
mapToolbarEnabled: false,
markers: Set.from(allMarkers),
),
),
}
void setCustomMapPin() async {
pinIcon = await BitmapDescriptor.fromAssetImage(
ImageConfiguration(devicePixelRatio: 2.5), 'assets/images/iconMap.png');
}
void mapCreated(controller) {
setState(() {
_controller = controller;
_location.getLocation();
//Adding markers to the screen.Calling the markers from different file.
myPlaces.forEach((e) {
allMarkers.add(Marker(
markerId: MarkerId(e.name),
draggable: false,
icon: pinIcon,
infoWindow: InfoWindow(
title: e.name,
snippet: e.address,
),
position: e.locationCoords,
onTap: () {
_pageController.animateToPage(myPlaces.indexOf(e),
duration: Duration(milliseconds: 300), curve: Curves.ease);
},
));
});
});
}
//moves the camera to pin location
void moveCamera() {...
}
You can do it with something like this
_markers.add(Marker(
consumeTapEvents: true,
position: _center,
infoWindow: InfoWindow(
title: 'New Marker',
snippet: '',
),
icon: markerImage, //you custom marker, instance of BitmapDescriptor
)
and than you instantiate the map with:
GoogleMap(
onMapCreated: (GoogleMapController controller) {
mapController = controller;
},
myLocationEnabled: locationEnable,
initialCameraPosition: CameraPosition(
target: _center,
zoom: 10.0,
),
mapType: MapType.normal,
markers: _markers,
)
var markerImage = await BitmapDescriptor.fromAssetImage(
ImageConfiguration(size: Size(96, 96)),
'assets/image/marker_image.png');
I am using Google Maps within my Flutter project. I am trying to parse two JSON files in my assets so that I can use their latitudes and longitudes in a Polyline and markers. The markers work fine but now I am adding another future to my Future builder for the polylines and I receive the following error:
The argument type LatLng can't be assigned to the parameter type List<LatLng>.
Future _future;
Future _futuree;
Future<String> loadString() async => await rootBundle.loadString('assets/busStops/stops_${widget.selectStation}.json');
List<Marker> allMarkers = [];
GoogleMapController _controller;
#override
void initState() {
// TODO: implement initState
super.initState();
//future 1
_future = loadString();
//future 2
_futuree = loadMyCoord();
}
Future<String> loadMyCoord() async {
var x = await rootBundle
.loadString('assets/route/coords_Centurion.json');
return x;
}
#override
Widget build(BuildContext context) {
createMarker(context);
return Scaffold(
appBar: AppBar(
title: Text("Bus Routes"),
centerTitle: true,
backgroundColor: Color.fromRGBO(59, 62, 64, 1),
actions: <Widget>[
FlatButton(
textColor: Colors.white,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => busStationList()),
);
},
child: Icon(Icons.add),
),
],
),
body: Stack(children: [
Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: FutureBuilder(
// Futures
future: Future.wait(
[
//[0]
_future,
//[1]
_futuree,
]
),
builder: (
context,
AsyncSnapshot<List<dynamic>> snapshot,
) {
// Check hasData once for all futures.
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
List<dynamic> parsedJson = jsonDecode(snapshot.data[0]);
allMarkers = parsedJson.map((element) {
return Marker(
icon: customIcon,
markerId: MarkerId(element["Latitude"].toString()),
position: LatLng(element['Latitude'] ?? 0.0,
element['Longitude'] ?? 0.0));
}).toList();
List<dynamic> parseJson = jsonDecode(snapshot.data[1]);
List<Polyline> allPolylinesByPosition = [];
parseJson.forEach((element){
List<dynamic> coords = element["coords"];
coords.forEach((i) {
double lat = double.tryParse(i["latitude"]);
double lng = double.tryParse(i["longitude"]);
allPolylinesByPosition.add(Polyline(
polylineId: PolylineId('lines'),
points: points: LatLng(lat ?? 0.0, lng ?? 0.0);
visible: true,
color: Colors.red
));
}
);
});
return GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(-26.1711459, 27.9002758), zoom: 9.0),
markers: Set.from(allMarkers),
onMapCreated: mapCreated,
polylines: Set.from(allPolylinesByPosition),
);
},
),
),
]),
);
}
void mapCreated(controller) {
setState(() {
_controller = controller;
});
}
Few things to note, points parameter of Polyline only accepts list of LatLng (List<LatLng>) and not LatLng.
This line should be changed in your code. Try adding a list of LatLng instead of passing a single LatLng instance in the points parameter.
points: LatLng(lat ?? 0.0, lng ?? 0.0);
Polyline.dart
class Polyline {
const Polyline({
#required this.polylineId,
this.consumeTapEvents = false,
this.color = Colors.black,
this.endCap = Cap.buttCap,
this.geodesic = false,
this.jointType = JointType.mitered,
this.points = const <LatLng>[],
this.patterns = const <PatternItem>[],
this.startCap = Cap.buttCap,
this.visible = true,
this.width = 10,
this.zIndex = 0,
this.onTap,
});
Hi I have now done the following , and pulling data but it is not showing on the map
List<dynamic> parseJson = jsonDecode(snapshot.data[1]);
Set<Polyline> allPolylinesByPosition = {};
parseJson.forEach((element) {
List<dynamic> coords = element["coords"];
coords.forEach((i) {
List<LatLng> latlng = [
LatLng( double.tryParse(i["latitude"]) ?? 0.0 ,double.tryParse(i["longitude"]) ?? 0.0)
];
allPolylinesByPosition.add(Polyline(
polylineId: PolylineId((_lastMapPosition.toString())),
points:latlng,
visible: true,
width: 4,
color: Colors.red
));
print(PolylineId);
}
);
});
return GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(-26.1711459, 27.9002758), zoom: 2.0),
markers: Set.from(allMarkers),
onMapCreated: mapCreated,
polylines: allPolylinesByPosition,
);
},
),
'''
I need to load maps in background because when I hit the tab with maps.dart for the first time, map is loading. It is looking bad so I want to use FutureBuilder to show CircularProgressIndicator() but I have no idea how to do this.
I know how to do it with Lists but in this case...
This maps.dart code:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
class Maps extends StatefulWidget {
#override
_MapsState createState() => _MapsState();
}
class _MapsState extends State<Maps> with AutomaticKeepAliveClientMixin {
Completer<GoogleMapController> _controller = Completer();
#override
void initState() {
super.initState();
}
double zoomValue = 9.0;
#override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
body: Stack(
children: <Widget>[
_buildGoogleMap(context),
_zoomMinusFunction(),
_zoomPlusFunction(),
],
),
);
}
Widget _zoomMinusFunction() {
return Align(
alignment: Alignment.topLeft,
child: IconButton(
icon: Icon(FontAwesomeIcons.searchMinus, color: Color(0xff6200ee)),
onPressed: () {
zoomValue--;
_minus(zoomValue);
}),
);
}
Widget _zoomPlusFunction() {
return Align(
alignment: Alignment.topRight,
child: IconButton(
icon: Icon(FontAwesomeIcons.searchPlus, color: Color(0xff6200ee)),
onPressed: () {
zoomValue++;
_plus(zoomValue);
}),
);
}
Future<void> _minus(double zoomValue) async {
final GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(target: LatLng(x, y), zoom: zoomValue)));
}
Future<void> _plus(double zoomValue) async {
final GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(target: LatLng(x, y), zoom: zoomValue)));
}
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(x, y), zoom: 9),
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
markers: {
aaa,
bbb,
},
),
);
}
#override
bool get wantKeepAlive => true;
}
Marker aaa = Marker(
markerId: MarkerId('aaa'),
position: LatLng(x, y),
infoWindow: InfoWindow(title: 'aaa', snippet: 'aaa'),
icon: BitmapDescriptor.defaultMarkerWithHue(
BitmapDescriptor.hueViolet,
),
);
Marker bbb = Marker(
markerId: MarkerId('bbb'),
position: LatLng(x, y),
infoWindow:
InfoWindow(title: 'bbb', snippet: 'bbb'),
icon: BitmapDescriptor.defaultMarkerWithHue(
BitmapDescriptor.hueViolet,
),
);
Sorry, I'm new to Flutter.
I know this is a little late, but if it still helps, this is what I have done.
_userLocation == null // If user location has not been found
? Center(
// Display Progress Indicator
child: CircularProgressIndicator(
backgroundColor: UniColors.primaryColour[500],
),
)
: GoogleMap(
// Show Campus Map
onMapCreated: _onMapCreated,
initialCameraPosition: // required parameter that sets the starting camera position. Camera position describes which part of the world you want the map to point at.
CameraPosition(
target: _userLocation,
zoom: defaultZoom,
tilt: 0.0),
scrollGesturesEnabled: true,
tiltGesturesEnabled: true,
trafficEnabled: false,
indoorViewEnabled: true,
compassEnabled: true,
rotateGesturesEnabled: true,
myLocationEnabled: true,
mapType: _currentMapType,
zoomGesturesEnabled: true,
cameraTargetBounds: new CameraTargetBounds(
new LatLngBounds(
northeast: uniCampusNE,
southwest: uniCampusSW,
),
),
minMaxZoomPreference:
new MinMaxZoomPreference(minZoom, maxZoom),
),
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]))));
}
});
}
}
The problem is how to infuse text overlap on the custom google map marker with text which represents the vehicle registration number.
I have tried to use this method to have the text overlay on the icon
builder: (context) =>()
But is not recognized at all.
class MapsDemo extends StatefulWidget {
#override
State createState() => MapsDemoState();
}
class MapsDemoState extends State<MapsDemo> {
GoogleMapController mapController;
//Map<PermissionGroup, PermissionStatus> permissions = await PermissionHandler().requestPermissions([PermissionGroup.contacts]);import 'package:permission_handler/permission_handler.dart';
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: GoogleMap(
onMapCreated: (GoogleMapController controller) {
mapController = controller;
},
),
),
],
),
floatingActionButton: FloatingActionButton(onPressed: () {
double mq1 = MediaQuery.of(context).devicePixelRatio;
String icon = "images/car.png";
if (mq1>1.5 && mq1<2.5) {icon = "images/car2.png";}
else if(mq1 >= 2.5){icon = "images/car3.png";}
print("Mq 1"+mq1.toStringAsFixed(5));
String iconPath="lib/assets/move#3x.png";
mapController.addMarker(
MarkerOptions(
position: LatLng(37.4219999, -122.0862462),
infoWindowText: InfoWindowText("TEST","TEST"),
icon: BitmapDescriptor.fromAsset(iconPath),
consumeTapEvents: true,
/*builder: (context) =>(
)*/
//icon:BitmapDescriptor.fromAsset(assetName)
),
);
mapController.addMarker(
MarkerOptions(
position: LatLng(38.4219999, -122.0862462),
infoWindowText: InfoWindowText("tt","adfaf"),
icon: BitmapDescriptor.fromAsset("lib/assets/logo.png"),
anchor: Offset(100,160),
//icon:BitmapDescriptor.fromAsset(assetName)
),
);
mapController.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
target: LatLng(37.4219999, -122.0862462),
zoom: 15.0,
),
),
);
})
);
}
}
What I have shown is the icon appear correctly if you notice the white space on the right of the icon is where I want the registration number to appear.
try this :
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
class MapsDemo extends StatefulWidget {
#override
State createState() => MapsDemoState();
}
class MapsDemoState extends State<MapsDemo> {
final Set<Marker> _markers = {};
void _onAddMarkerButtonPressed() {
print('in _onAddMarkerButtonPressed()');
setState(() {
_markers.add(Marker(
// This marker id can be anything that uniquely identifies each marker.
markerId: MarkerId("111"),
position: LatLng(30.666, 76.8127),
infoWindow: InfoWindow(
title: "bingo! This works",
),
icon: BitmapDescriptor.defaultMarker,
));
});
print('setState() done');
}
GoogleMapController mapController;
//Map<PermissionGroup, PermissionStatus> permissions = await PermissionHandler().requestPermissions([PermissionGroup.contacts]);import 'package:permission_handler/permission_handler.dart';
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: GoogleMap(
markers: _markers,
onMapCreated: (GoogleMapController controller) {
mapController = controller;
},
initialCameraPosition:
CameraPosition(target: LatLng(30.666, 76.8127), zoom: 15),
),
),
],
),
floatingActionButton: FloatingActionButton(onPressed: () {
print('in fab()');
double mq1 = MediaQuery.of(context).devicePixelRatio;
_onAddMarkerButtonPressed();
mapController.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
target: LatLng(30.666, 76.8127),
zoom: 15.0,
),
),
);
}));
}
}
I kludged/solved this by creating a function which returned a , whose returned and resolved value I then passed in as the icon when initializing a Marker:
Sorry to say that I don't remember why I padded the method with the magic 40 and 20 constants. Probably calculated by visual test with what I was rendering at the time.
Future<BitmapDescriptor> createCustomMarkerBitmap(/* your args here */) async {
PictureRecorder recorder = new PictureRecorder();
Canvas c = new Canvas(recorder);
/* Do your painting of the custom icon here, including drawing text, shapes, etc. */
Picture p = recorder.endRecording();
ByteData pngBytes = await (await p.toImage(
tp.width.toInt() + 40, tp.height.toInt() + 20))
.toByteData(format: ImageByteFormat.png);
Uint8List data = Uint8List.view(pngBytes.buffer);
return BitmapDescriptor.fromBytes(data);
}
Then when creating the marker, you can pass in the BitmapDescriptor as the icon, like so:
createCustomMarkerBitmap(...).then((BitmapDescriptor bitmapDescriptor) {
_markers.add(new Marker(
/* in addition to your other properties: */
icon: bitmapDescriptor,
));
});
or:
BitmapDescriptor bitmapDescriptor = await createCustomMarkerBitmap(...);
Marker marker = Marker(
/* in addition to your other properties: */
icon: bitmapDescriptor
);
Let me know if that helps. Gl!
I have found this answer for github issue
I found myself on this exact stackoverflow page multiple times this year. So, I decided to go and make my first Flutter Package and created this. If your objective is to add a simple and clear text to map marker, this would do it.
https://pub.dev/packages/label_marker
Usage
markers.addLabelMarker(LabelMarker(
label: "TextToShow",
markerId: MarkerId("idString"),
position: LatLng(10.0, 11.0),
backgroundColor: Colors.green,
)).then((value) {
setState(() {});
},
);