I am trying to set images coming from my database as icons for every point in the map. So far it kind of works , but it is to slow to load images and I believe this would not be scalable in the future. Futhermore, the app, at least in debug mode, crashes with out of memory issues.
Currently, I am using flutter_maps package to display my map:
return FlutterMap(
options:
MapOptions(
//center: tomtomCenter,
zoom: 1.0),
layers: [
TileLayerOptions(
minNativeZoom: 1.0,
backgroundColor: Colors.transparent,
urlTemplate:
"https://api.tomtom.com/map/1/tile/basic/main/"
"{z}/{x}/{y}.png?key={apiKey}",
attributionBuilder: (_) {
return const Text("© OpenStreetMap contributors");
},
additionalOptions: {"apiKey": TOMTOM_APIKEY},
),
MarkerLayerOptions(
markers: [
//_buildMarker( tomtomCenter, 'tomtomCenter'),
for (var mark in snapshot.data)
//{
_buildMarker(LatLng(mark['latitude'], mark['longitude']), 'Others', mark['DogImg'].url.toString())
//}
],
),
],
);
}
every point is defined in this function:
Marker _buildMarker(LatLng latLng, String currentLocation, String dogimg) {
return Marker(
point: latLng,
width: 10.0,
height: 10.0,
//anchorPos: AnchorPos.exactly(Anchor(2, 2)),
builder: (BuildContext context) =>
ClipRRect(child: Image.network(dogimg),)
);
}
I do not think that loading that amount of images through http request is the best idea, right?
I saw in other packages like google maps that load images (in that case from assets but there should be also for network requests) which look lighter
BitmapDescriptor markerbitmap = await BitmapDescriptor.fromAssetImage(
ImageConfiguration(),
"assets/images/bike.png",
);
Related
I am completely new to Flutter, but I need to develop a mobile app for a university project using Flutter & Dart. I want to add a Pie Chart to my application and so I imported the flutter_charts package. I have gotten it to sort of work. Below is the code currently which produces a working result.
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:sa_voting_app/Charts/main_series.dart';
class VoterChart extends StatelessWidget {
const VoterChart({Key? key, required this.data}) : super(key: key);
final List<VoterSeries> data;
#override
Widget build(BuildContext context) {
List<charts.Series<VoterSeries, String>> series = [
charts.Series(
id: "Voters",
data: data,
domainFn: (VoterSeries series, _) => series.party,
measureFn: (VoterSeries series, _) => series.voters,
colorFn: (VoterSeries series, _) => series.barColor)
];
return Container(
height: MediaQuery.of(context).size.height,
padding: const EdgeInsets.all(20),
child: SizedBox(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
Text(
"Current Leader Board for Parties:",
style: Theme.of(context).textTheme.bodyText1,
),
Expanded(
child: charts.PieChart(series,animate: true),
),
],
),
),
),
),
);
}
}
It produces the following output:
I want to then add labels to the PieChart. So I googled a few tutorials and came up with this code:
Expanded(
child: charts.PieChart(series,
defaultRenderer: charts.ArcRendererConfig(
customRendererId: 'mainChartRender',
arcRendererDecorators: [
charts.ArcLabelDecorator(
labelPosition: charts.ArcLabelPosition.inside),
],
),
animate: true),
),
However as soon as I add this code and try to run my application again the following happens:
As you can see the Chart dissapears, I also get an exception in the box.dart file which appears as follows:
This is the code where the exception appears:
Size get size {
assert(hasSize, 'RenderBox was not laid out: ${toString()}');
assert(() {
final Size? _size = this._size;
if (_size is _DebugSize) {
assert(_size._owner == this);
if (RenderObject.debugActiveLayout != null &&
!RenderObject.debugActiveLayout!.debugDoingThisLayoutWithCallback) {
assert(
debugDoingThisResize || debugDoingThisLayout || _computingThisDryLayout ||
(RenderObject.debugActiveLayout == parent && _size._canBeUsedByParent),
'RenderBox.size accessed beyond the scope of resize, layout, or '
'permitted parent access. RenderBox can always access its own size, '
'otherwise, the only object that is allowed to read RenderBox.size '
'is its parent, if they have said they will. It you hit this assert '
'trying to access a child\'s size, pass "parentUsesSize: true" to '
"that child's layout().",
);
}
assert(_size == this._size);
}
return true;
}());
return _size!;
}
I have tried looking at various places online to try and get a solution, but most stuff that references the "Render Box was not laid out error" is in regards to putting a ListView/GridView into a Column/Row. There was two of the following posts that reference similar issues: Flutter GoogleChart Pie chart does not render (I followed the very few solutions suggested here, but none yielded results.) There was also this post, but again its suggested solutions did not fix my issue.
Being new to Flutter I do not have any idea where to even begin troubleshooting. I would greatly appreciate it if someone could guide me in the right direction or help explain what exactly is causing the error. Thank you very much in advance for your time.
I faced similar issue as well.
I don't know why but it happens when we use defaultRenderer
After searching on google a bit I found a work around.
I don't know why it works, but it worked in my case at least.
Here is link to Source
You have to add the type parameter of the PieChart
so as you have series of type charts.Series<VoterSeries, String>> you updated code should look like
Expanded(
child: charts.PieChart<String>(series,
defaultRenderer: charts.ArcRendererConfig(
customRendererId: 'mainChartRender',
arcRendererDecorators: [
charts.ArcLabelDecorator(
labelPosition: charts.ArcLabelPosition.inside),
],
),
animate: true),
),
Notice a type parameter <String> is added in
child: charts.PieChart<String>(series,
Hope it helps.
I am developing a simple application that spins a fortune wheel based on Flutter_Fortune_Wheel. So far everything works as expected except I have kept the size of the wheel small to accomodate other screen assets and the TriangleIndicator size is too large. How do I specify a smaller sized TriangleIndicator?
Applicable code follows:
FortuneWheel(
animateFirst: false,
onAnimationEnd: () {
widget.callback(wheelContents[letterInt]);
if (wheelContents.length > 1) {
wheelContents.removeAt(letterInt);
} else {
print('***** Puzzle Solved!*****');
}
},
selected: selected.stream,
indicators: const <FortuneIndicator>[
FortuneIndicator(
alignment: Alignment
.topCenter, // <-- changing the position of the indicator
child: TriangleIndicator(
color:
Colors.amber, // <-- changing the color of the indicator
),
),
],
items: [
for (var ltr in wheelContents) FortuneItem(child: Text(ltr)),
],
),
TIA
I'm using syncfusion_flutter_maps to draw an arc on the map between two locations i want to get the center (latitude,longitude) of this arc.
SfMaps(
layers: [
MapShapeLayer(
source: dataSource,
sublayers: [
MapArcLayer(
arcs: List<MapArc>.generate(
data.length,
(int index) {
return MapArc(
from: data[index].from,
to: data[index].to,
width: 4,
);
},
).toSet(),
),
],
zoomPanBehavior: zoomPanBehavior,
)
The result will be something like this
or this
I found this library: https://pub.dev/packages/flutter_map_picker
I looked through his code and tried figuring out how he initiates drawing. What he accomplishes is far more complicated than I need, and I can't figure out the first step of what he did. I also don't want to take the guy's code. Can anyone explain how to accomplish this?
I just want to be able to circle objects on my map. There seems to be a polyline solution but it's just straight lines from a list of coordinates, not exactly what I'm looking for.
A Stack widget with GoogleMap and CustomPaint will let you draw anything you want on top of the map.
Stack(
children: <Widget>[
_position == null
? Text('Waiting for location . .')
: GoogleMap(
liteModeEnabled: false,
compassEnabled: true,
mapType: MapType.hybrid,
markers: Set<Marker>.of(markers.values),
initialCameraPosition: CameraPosition(
target: LatLng(_position.latitude, _position.longitude),
zoom: 17,
tilt: 0,
),
onMapCreated: (GoogleMapController controller) {
_mapController = controller;
// trigger initial update and paint of landmarks
_updateLandmarks();
},
onCameraMove: (CameraPosition position) {
_updateLandmarks();
},
),
CustomPaint(
foregroundPainter: MapPainter(_landmarksMap),
),
],
)
You have to convert map coordinates to device screen coordinates. Google has a cookbook on how to do that except it does not work in Flutter since the map plugin does not expose the complete API. But there is a way to do it of course.
void _updateLandmarks() async {
double dpi = MediaQuery.of(context).devicePixelRatio;
LatLngBounds bounds = await _mapController.getVisibleRegion();
ScreenCoordinate topRight = await _mapController.getScreenCoordinate(bounds.northeast);
ScreenCoordinate bottomLeft = await _mapController.getScreenCoordinate(bounds.southwest);
_landmarksMap.values.forEach((element) async {
ScreenCoordinate sc = await _mapController.getScreenCoordinate(LatLng(element.pos.latitude, element.pos.longitude));
element.screenPoint.x = ((sc.x - bottomLeft.x) / dpi).floor();
element.screenPoint.y = ((sc.y - topRight.y) / dpi).floor();
});
setState(() {});
}
You can read here for more details: https://aperico.com/google-maps-with-custom-paint-in-flutter/
How to fit polylines to street curves in google maps flutter?
I did being playing with Polylines in google_maps_flutter for 2 months and I have this doubts:
Polylines do not follow the street curves or the highways.
Polylines has the OnTap callback but, on multi-polylines I can not get any ID or attribute to distinguis who I tapped.
can any one give me a hand with this?
I am new in Flutter and I am using the Directions API from Google. Maybe is not the right API to solve this problem.
I need that polyline set follow the street curves.
Polylines in google_maps_flutter
P.S: Sorry if my code bleed your eyes!
google_maps_flutter widget:
GoogleMap(
onMapCreated: (controller) {
_mapController = controller;
},
initialCameraPosition: CameraPosition(
target: getCurrentLocation(),
zoom: 15,
),
mapType: _currentMapType,
myLocationEnabled: true,
myLocationButtonEnabled: false,
compassEnabled: true,
rotateGesturesEnabled: true,
markers: _markers,
polylines: _polyline,
)
Set state to show the polyline and markers:
setState(
() {
_markers.clear();
for (var point in itinerary) {
_markers.add(
Marker(
markerId: MarkerId("stop ${point.latitude}"),
position: LatLng(point.latitude, point.longitude),
infoWindow: InfoWindow(title: point.address),
),
);
}
_polyline.clear();
_polyline.add(
flutter.Polyline(
polylineId: PolylineId("route"),
points: ccc,
width: 8,
color: Colors.red,
geodesic: true,
jointType: JointType.round,
),
);
_mapController.animateCamera(
CameraUpdate.newLatLngZoom(
LatLng(origin.lat, origin.lng), 13.0),
);
},
);
Google Directions API Call:
GoogleMapsDirections(apiKey: apiKey).directions(origin, destination, waypoints: itinerary, ).then((DirectionsResponse response) { return response }
I got some advice from Github member that told me to try SnapToRoad, now I get more details about the route, but the highways are still helicopter's travel
A simple GET to https://roads.googleapis.com/v1/snapToRoads whit the API_KEy and some points of my previus polyline helps.
Here is the link of SnapToRoad
That's because the polyline it's just a line that you draw, to do what you want need to make a route between points and using that generated coordinates make a polyline.
Check this tutorial that i found: https://www.developerlibs.com/2018/08/flutter-how-can-draw-route-on-google.html
try this pub: google_map_polyline