snap markers to nearest polyline point Google Maps flutter - flutter

I am writing a simple bus tracking app for my university shuttles. I have plotted out the bus GPS as navigation arrows along with the route on the map. Now as the actual GPS coordinate is a little of from the real location of bus than the plotted route, it is slightly off the road. Is there any way or method that I can call to snap these markers to the polyline nearest point in google maps flutter plugin? I just wanted to know if there is anything already in place that I am missing. I would be willing to write the custom nearest neighbor logic if necessary. Thanks!

I have done using locationIndexOnPath, computeDistanceBetween, computeHeading.
Step 1. add this function to get nearest polyline segment index based on you current location. pass your polyline coordinates list and current location. below function return index of given polyline coordinates list.
int getEdgeIndex(List<mt.LatLng> _coordinates, mt.LatLng currentLocation) {
final int edgeIndex1 = mt.PolygonUtil.locationIndexOnPath(
currentLocation, _coordinates, true,
tolerance: 1);
final int edgeIndex2 = mt.PolygonUtil.locationIndexOnPath(
currentLocation, _coordinates, true,
tolerance: 2);
final int edgeIndex6 = mt.PolygonUtil.locationIndexOnPath(
currentLocation, _coordinates, true,
tolerance: 6);
final int edgeIndex10 = mt.PolygonUtil.locationIndexOnPath(
currentLocation, _coordinates, true,
tolerance: 10);
final int edgeIndex15 = mt.PolygonUtil.locationIndexOnPath(
currentLocation, _coordinates, true,
tolerance: 15);
int finalIndex = -1;
if (edgeIndex1 >= 0) {
finalIndex = edgeIndex1;
} else if (edgeIndex2 >= 0) {
finalIndex = edgeIndex2;
} else if (edgeIndex6 >= 0) {
finalIndex = edgeIndex6;
} else if (edgeIndex10 >= 0) {
finalIndex = edgeIndex10;
} else if (edgeIndex15 >= 0) {
finalIndex = edgeIndex15;
}
print(
"getEdgeIndex: index : $edgeIndex1, $edgeIndex2, $edgeIndex6, $edgeIndex10, $edgeIndex15, $finalIndex");
return finalIndex;
}
Step 2. Now add this function to get snap LatLag to snap you current marker in centre of polyline route.
Map<String, dynamic> getSnapLatLng(LatLng currentLocation) {
final currentLocationMT =
mt.LatLng(currentLocation.latitude, currentLocation.longitude);
if (coordinatesMT.isEmpty) {
for (LatLng latLng in coordinates) {
coordinatesMT.add(mt.LatLng(latLng.latitude, latLng.longitude));
}
}
final int finalIndex = getEdgeIndex(coordinatesMT, currentLocationMT);
if (finalIndex >= 0) {
final snappedLatLng2 = (finalIndex < coordinatesMT.length - 1)
? coordinatesMT[finalIndex + 1]
: currentLocationMT;
final snappedLatLng = coordinatesMT[finalIndex];
final distanceM2 = mt.SphericalUtil.computeDistanceBetween(
snappedLatLng, currentLocationMT);
double heading = mt.SphericalUtil.computeHeading(
snappedLatLng2,
snappedLatLng,
);
final extrapolated =
mt.SphericalUtil.computeOffset(snappedLatLng, -distanceM2, heading);
print(
"snapToPolyline:distanceM $distanceM2, $heading, $finalIndex, ${coordinatesMT.length}");
return {
"index": finalIndex,
"latLng": LatLng(extrapolated.latitude, extrapolated.longitude)
};
}
return {"index": finalIndex, "latLng": currentLocation};
}
NOTE: I have used https://pub.dev/packages/maps_toolkit this package for locationIndexOnPath, computeDistanceBetween, computeHeading.

Related

Moving Car Animation Using Mapbox in flutter

I've implementing MabBox SDK with one of my flutter app. It has car live tracking screen, which will update car marker position on map based on location received. Here we would like to show car moving animation like this .
I've gone through the MabBox documents, Couldn't find any related document for our use cases. Then I've gone through google's flutter_animarker which doesn't support Mabbox. Anyone please help me on this.
I've finished car moving animation. Here is the final code.
import 'package:flutter/animation.dart';
import 'dart:math' as math;
LatLng? oldLatLng;
bool isCarAnimating = false;
onLocationChange(String latLng) async {
currentLatLng = LatLng(
double.parse(latLng.split(',')[0]), double.parse(latLng.split(',')[1]));
if (cabMarkerSymbol != null && !isCarAnimating)
_animateCabIcon(oldLatLng!, currentLatLng!);
}
_animateCabIcon(LatLng start, LatLng end) async {
try {
AnimationController controller =
AnimationController(vsync: this, duration: Duration(seconds: 3));
Animation animation;
var tween = Tween<double>(begin: 0, end: 1);
animation = tween.animate(controller);
animation.addStatusListener((status) {
if (status == AnimationStatus.completed) {
oldLatLng = end;
isCarAnimating = false;
} else if (status == AnimationStatus.forward) {
isCarAnimating = true;
}
});
controller.forward();
var bearing = getBearing(start, end);
animation.addListener(() async {
var v = animation.value;
var lng = v * end.longitude + (1 - v) * start.longitude;
var lat = v * end.latitude + (1 - v) * start.latitude;
var latLng = LatLng(lat, lng);
var carSymbolOptions = SymbolOptions(
geometry: latLng,
iconRotate: bearing,
);
await _completer.future
.then((map) => map.updateSymbol(carMarkerSymbol!, carSymbolOptions));
});
} catch (e) {
print(e);
}
}
double getBearing(LatLng start, LatLng end) {
var lat1 = start.latitude * math.pi / 180;
var lng1 = start.longitude * math.pi / 180;
var lat2 = end.latitude * math.pi / 180;
var lng2 = end.longitude * math.pi / 180;
var dLon = (lng2 - lng1);
var y = math.sin(dLon) * math.cos(lat2);
var x = math.cos(lat1) * math.sin(lat2) -
math.sin(lat1) * math.cos(lat2) * math.cos(dLon);
var bearing = math.atan2(y, x);
bearing = (bearing * 180) / math.pi;
bearing = (bearing + 360) % 360;
return bearing;
}

Flutter AR - add pin on real time position

I'm trying to implement AR on flutter platform for mobile devices using ar_flutter_plugin. I don't know how calculate position for ARNode object. The method for adding object to real time :
Future<void> addPointsOnmap() async {
var location = await Geolocator.getCurrentPosition();
var data = await GetObjekti.getResults(
location.latitude.toString() + "," + location.longitude.toString(), 2);
List<Result> results = data["results"];
for (var i = 0; i < results.length; i++) {
//I need to calculate value of position
ARNode node = ARNode(
type: NodeType.localGLTF2,
uri: "assets/Chicken_01/Chicken_01.gltf",
scale: Vector3(100.0, 100.0, 100.0),
position: Vector3(0.0, 0.0, 0.0),
rotation: Vector4(1.0, 0.0, 0.0, 0.0));
results[i].arNodeName = node.name;
bool? addNode = await arObjectManager.addNode(node);
if (addNode!){
nodes.add(node);
}
}
}
Method getResults fetchs data from API and example of one object from response is:
{
"distance": 0.48079831661545036,
"centroid": {
"lon": 16.343588998,
"lat": 46.294568693
},
"label": "Some label",
"id": 106405,
"object_id": 10575,
"feature_class_id": 1431
}
Where distance is calculated distance from the geolocation of user to place from result in km (kilometers) and centroid contains geo longitude and latitude. Any suggestion or help are welcome.

Distance calculation Flutter background Location

I am trying to develop a Location service-based Distance calculation app. the problem is I need this to be run when the app is in the background as well. so I used the following plugin to do so.
https://pub.dev/packages/background_location
when this runs on AVD nothing happened but worked fine. but when run on some devices I got the wrong calculations. I have noticed that this happens when the app is in the background this is. following is a partial recreation of mine. I just want to know if my code get any error before posting this as an issue
Future<void> startLocationUpdate() async {
var permission = await Permission.locationAlways.isGranted;
if (!permission) {
var t = await Permission.locationAlways.request();
}
oldPosition2 = Location(
longitude: currentPosition.longitude, latitude: currentPosition.latitude);
isWaited = false;
waitButtonText = "WAIT";
BackgroundLocation.stopLocationService();
BackgroundLocation.setAndroidConfiguration(2000);
await BackgroundLocation.setAndroidNotification(
title: "XXXXXXXXXXXXXXXXX",
message: "XXXXXXXXXXXXXXXXXX",
icon: "XXXXXXXXXXXXXXXXXX",
);
//print('Inside startLocationUpdate');
await BackgroundLocation.startLocationService(distanceFilter: 20);
print('Inside startLocationUpdate 1');
BackgroundLocation.getLocationUpdates((location) {
try {
currentPosition = location;
LatLng pos = LatLng(location.latitude, location.longitude);
var rotation = MapKitHelper.getMarkerRotation(oldPosition2.latitude,
oldPosition2.longitude, pos.latitude, pos.longitude);
Marker movingMaker = Marker(
markerId: MarkerId('moving'),
position: pos,
icon: movingMarkerIcon,
rotation: rotation,
infoWindow: InfoWindow(title: 'Current Location'),
);
setState(() {
CameraPosition cp = new CameraPosition(target: pos, zoom: 17);
rideMapController.animateCamera(CameraUpdate.newCameraPosition(cp));
_markers.removeWhere((marker) => marker.markerId.value == 'moving');
_markers.add(movingMaker);
this.accuracy = location.accuracy.toStringAsFixed(0);
totalSpeed = location.speed;
totalDistance = totalDistance +
CalDistance(oldPosition2 != null ? oldPosition2 : location,
location, DistanceType.Kilometers);
var totalDistanceAdj = totalDistance != 0 ? totalDistance : 1;
//totalFare = 50 + (kmPrice * totalDistanceAdj);
print("distance $totalDistance");
});
oldPosition2 = location;
updateTripDetails(location);
Map locationMap = {
'latitude': location.latitude.toString(),
'longitude': location.longitude.toString(),
};
rideRef = FirebaseDatabase.instance
.reference()
.child("rideRequest/${widget.tripDetails.rideID}");
rideRef.child('driver_location').set(locationMap);
} catch (e) {
FirebaseService.logtoGPSData('Error in updates ${e}');
}
});
}
and the CalDistance method as follows
double CalDistance(Location pos1, Location pos2, DistanceType type) {
print("pos1 : ${pos1.latitude} pos2: ${pos2.latitude}");
double R = (type == DistanceType.Miles) ? 3960 : 6371;
double dLat = this.toRadian(pos2.latitude - pos1.latitude);
double dLon = this.toRadian(pos2.longitude - pos1.longitude);
double a = sin(dLat / 2) * sin(dLat / 2) +
cos(this.toRadian(pos1.latitude)) *
cos(this.toRadian(pos2.latitude)) *
sin(dLon / 2) *
sin(dLon / 2);
double c = 2 * asin(min(1, sqrt(a)));
double d = R * c;
//d = (d*80)/100;
return d;
}
double toRadian(double val) {
return (pi / 180) * val;
}
Any help or hint would be much appreciated

Flutter LatLngBounds not showing accurate place

I am trying to show all of my markers into the viewport using my flutter google maps. But it seems not working in my case. I have tried so far as below:
_controller.animateCamera(CameraUpdate.newLatLngBounds(
LatLngBounds(
southwest: LatLng(23.785182, 90.330702),
northeast: LatLng(24.582782, 88.821163),
),
100
));
LatLngBounds boundsFromLatLngList(List<LatLng> list) {
assert(list.isNotEmpty);
double x0, x1, y0, y1;
for (LatLng latLng in list) {
if (x0 == null) {
x0 = x1 = latLng.latitude;
y0 = y1 = latLng.longitude;
} else {
if (latLng.latitude > x1) x1 = latLng.latitude;
if (latLng.latitude < x0) x0 = latLng.latitude;
if (latLng.longitude > y1) y1 = latLng.longitude;
if (latLng.longitude < y0) y0 = latLng.longitude;
}
}
return LatLngBounds(northeast: LatLng(x1, y1), southwest: LatLng(x0, y0));
}
As i have seen, it just always show the map of North Atlantic Ocean
Is there any solution regarding this issue or it is just under development in Flutter ?. thanks in advance
I'm facing the exact same issue on Android (works fine on iOS) when I animate the map with CameraUpdate.newLatLngBounds. It repositions to North Pacific Ocean immediately after setting the bounds, not sure what's causing this but here's a workaround -
Instead of setting the map position using LatLngBounds, you can calculate the centre of the bounds you want to set
// the bounds you want to set
LatLngBounds bounds = LatLngBounds(
southwest: LatLng(23.785182, 90.330702),
northeast: LatLng(24.582782, 88.821163),
);
// calculating centre of the bounds
LatLng centerBounds = LatLng(
(bounds.northeast.latitude + bounds.southwest.latitude)/2,
(bounds.northeast.longitude + bounds.southwest.longitude)/2
);
// setting map position to centre to start with
controller.moveCamera(CameraUpdate.newCameraPosition(CameraPosition(
target: centerBounds,
zoom: 17,
)));
zoomToFit(controller, bounds, centerBounds);
Once you set the map position to the centre of the bounds (and zoomed in), you then need to keep zooming out till the visible map region covers the bounds you want to set. You can get the visible map region with controller.getVisibleRegion(). Here's the implementation -
Future<void> zoomToFit(GoogleMapController controller, LatLngBounds bounds, LatLng centerBounds) async {
bool keepZoomingOut = true;
while(keepZoomingOut) {
final LatLngBounds screenBounds = await controller.getVisibleRegion();
if(fits(bounds, screenBounds)){
keepZoomingOut = false;
final double zoomLevel = await controller.getZoomLevel() - 0.5;
controller.moveCamera(CameraUpdate.newCameraPosition(CameraPosition(
target: centerBounds,
zoom: zoomLevel,
)));
break;
}
else {
// Zooming out by 0.1 zoom level per iteration
final double zoomLevel = await controller.getZoomLevel() - 0.1;
controller.moveCamera(CameraUpdate.newCameraPosition(CameraPosition(
target: centerBounds,
zoom: zoomLevel,
)));
}
}
}
bool fits(LatLngBounds fitBounds, LatLngBounds screenBounds) {
final bool northEastLatitudeCheck = screenBounds.northeast.latitude >= fitBounds.northeast.latitude;
final bool northEastLongitudeCheck = screenBounds.northeast.longitude >= fitBounds.northeast.longitude;
final bool southWestLatitudeCheck = screenBounds.southwest.latitude <= fitBounds.southwest.latitude;
final bool southWestLongitudeCheck = screenBounds.southwest.longitude <= fitBounds.southwest.longitude;
return northEastLatitudeCheck && northEastLongitudeCheck && southWestLatitudeCheck && southWestLongitudeCheck;
}
Had the same issue the problem for me:
I didn't really gave the southwest and northeast coordinates but:
NorthWest and SouthEast. iOS handled this normally but android zoomed on the Atlantic.
After fixing that like:
final highestLat = points.map((e) => e.latitude).reduce(max);
final highestLong = points.map((e) => e.longitude).reduce(max);
final lowestLat = points.map((e) => e.latitude).reduce(min);
final lowestLong = points.map((e) => e.longitude).reduce(min);
final lowestLatLowestLong = LatLng(lowestLat, lowestLong);
final highestLatHighestLong = LatLng(highestLat, highestLong);
final getRouteBoundsCameraUpdate = CameraUpdate.newLatLngBounds(LatLngBounds(southwest: lowestLatLowestLong, northeast: highestLatHighestLong), 25.0);
I also had this issue, try swapping the southwest value with northeast value
i found this way that work for me perfectly .
Future<void> updateCameraLocation(
LatLng source,
LatLng destination,
GoogleMapController mapController,
) async {
if (mapController == null) return;
LatLngBounds bounds;
if (source.latitude > destination.latitude &&
source.longitude > destination.longitude) {
bounds = LatLngBounds(southwest: destination, northeast: source);
} else if (source.longitude > destination.longitude) {
bounds = LatLngBounds(
southwest: LatLng(source.latitude, destination.longitude),
northeast: LatLng(destination.latitude, source.longitude));
} else if (source.latitude > destination.latitude) {
bounds = LatLngBounds(
southwest: LatLng(destination.latitude, source.longitude),
northeast: LatLng(source.latitude, destination.longitude));
} else {
bounds = LatLngBounds(southwest: source, northeast: destination);
}
CameraUpdate cameraUpdate = CameraUpdate.newLatLngBounds(bounds, 70);
return checkCameraLocation(cameraUpdate, mapController);
}
Future<void> checkCameraLocation(
CameraUpdate cameraUpdate, GoogleMapController mapController) async {
mapController.animateCamera(cameraUpdate);
LatLngBounds l1 = await mapController.getVisibleRegion();
LatLngBounds l2 = await mapController.getVisibleRegion();
if (l1.southwest.latitude == -90 || l2.southwest.latitude == -90) {
return checkCameraLocation(cameraUpdate, mapController);
}
}
And use by this line :
await updateCameraLocation(source, destination, controller);

Leaflet playback place marker

I am using the playback plugin and i am using it on an image overlay.
https://github.com/hallahan/LeafletPlayback
I need to scale the floor map before placing the marker. with the plugin the marker is placed some where outside of the floor map.
I am able to solve the issue for GPS tracking, where i have written a function to scale the map and place the marker inside pointToLayer method of layer property.
I want to do the same for marker too. any help is appreciated.
const playbackOptions = {
playControl: true,
dateControl: true,
orientIcons: true,
fadeMarkersWhenStale: true,
// layer and marker options
layer: {
pointToLayer(featureData, latlng) {
const { lat, lng } = latlng;
let result = {};
if (featureData && featureData.properties && featureData.properties.path_options) {
result = featureData.properties.path_options;
}
if (!result.radius) {
result.radius = 5;
}
const scaleX = width / details.width;
const scaleY = height / details.length;
const m = {
x: lat * scaleX,
y: lng * scaleY,
};
const iconCls = 'asset-icon';
const item = L.marker(self.map.unproject([m.x, m.y], self.map.getMaxZoom()), {
icon: makeMarker(iconCls, 0),
opacity: 0.9,
type: 'asset',
lat,
lng,
});
item.bindTooltip(`<p>${lat}, ${lng}`, { className: 'asset-label', offset: [0, 0] });
return item;
}
},
marker: {
getPopup(featureData) {
let result = '';
if (featureData && featureData.properties && featureData.properties.title) {
result = featureData.properties.title;
}
return result;
}
}
};
If you retrieve actual GPS coordinates, it would probably be easier to actually do the reverse, i.e. to georeference your image overlay once for good, instead of trying to fiddle with the geographic coordinates of each of the feature you try to show relatively to your image.