How to update marker position google maps flutter - flutter

I want to use a custom marker as user position. I am listening to location event and on each move I want to set new lat/lon on this marker. However I don't see any options to update markers position. How can I achieve this? I've tried removing the current marker and adding a new one, but there's ugly flash effect which I do not want.
final marker = Marker(
markerId: MarkerId('1'),
position: LatLng(_latitude, _longitude),
icon: await customIcon()
);
setState(() {
_markers.add(marker);
});
_location.onLocationChanged.listen((event) async {
//here I want to update the marker lat lng with new event.latitude and event.longitude
});

Try the following
_location.onLocationChanged.listen((event) async {
final newMarker = Marker(
markerId: MarkerId('1'),
position: LatLng(event.latitude, event.longitude),
icon: await customIcon()
);
final oldMarkerIndex = _markers.indexWhere((marker) => marker.markerId == MarkerId('1'));
if(oldMarkerIndex >= 0) { // If it exists
setState(() {
_markers[oldMarkerIndex] = newMarker;
});
}
});

Related

How to add user info above location marker in flutter

I want to display drivers' info above the markers on the map, like driver name and car name. but i do not know how to do so.
I am using flutter, flutter geofire and firebase realtime database
My code is
displayActiveDriversOnUserMap()
{ setState((){
markersSet.clear();
circleSet.clear();
Set<Marker> driversMarkerSet = Set<Marker>();
for(ActiverNearbyAvailableDrivers eachDriver in GeoFireAssistant.activeNearbyAvailableDriversList)
{
LatLng eachDriverActivePosition = LatLng(eachDriver.locationLatitude!, eachDriver.locationLongitude!);
Marker marker = Marker(
markerId: MarkerId(eachDriver.driverId!),
position: eachDriverActivePosition,
icon: activeNearByIcon!,
rotation: 360,
);
driversMarkerSet.add(marker);
}
setState ((){
markersSet = driversMarkerSet;
});
});
}
createActiveNearByDriverIconMarker()
{
if(activeNearByIcon == null)
{
ImageConfiguration imageConfiguration = createLocalImageConfiguration(context, size: const Size(2, 2));
BitmapDescriptor.fromAssetImage(imageConfiguration, "images/car.png").then((value)
{
activeNearByIcon = value;
});
}
}
}
screenshot of map

Cannot add more than one marker in google map (flutter)

I am trying to add multiple markers in google map but once I call the function, only the last marker is shown. What am I missing?
I read here that I must pass a dynamic markerId, which I think I am already doing but for some reason I cannot get the first marker, always the last one.
Note: It's not a typo type of issue - if I remove the last marker, the first marker is being displayed. So it must have something to do with the function overwriting the first marker with the last one:
void Markers() async {
var firstPath = "img/first.png";
final Uint8List firstIcon = await getBytesFromAsset(firstPath, 50);
var lastPath = "img/last.png";
final Uint8List lastIcon = await getBytesFromAsset(lastPath, 50);
_listmarkers = Set<Marker>();
_listmarkers.add(Marker(
markerId: MarkerId(_navigationList.first.userId.toString()),
position: LatLng(_navigationList.first.latitude,
_navigationList.first.longitude),
icon: BitmapDescriptor.fromBytes(firstIcon),
));
_listmarkers.add(Marker(
markerId: MarkerId(_navigationList.last.userId.toString()),
position: LatLng(_navigationList.last.latitude,
_navigationList.last.longitude),
icon: BitmapDescriptor.fromBytes(lastIcon),
));
setState(() {});
}
void createMap() {
if (_navigationList.isNotEmpty) {
_postsController.add(1);
LatLngBounds bound = boundsFromLatLngList(_navigationList);
Markers();
}
}
Most probably
_navigationList.last.userId.toString() == _navigationList.first.userId.toString()

Flutter google map custom marker with gesture detector

Now I am using google_maps_flutter to build my map, but it only has onTap function in Marker, how can I implement another gesture, like long press or tap down etc.
Marker(
markerId: MarkerId('1'),
position: LatLng(25.032970, 121.565415),
icon: await getMarkerIcon("imageUrl", Size(120.0, 120.0)),
consumeTapEvents: true,
onTap: () {
print('onPress');
},
onLongPress?
),
BitmapDescriptor customIcon;
// make sure to initialize before map loading
BitmapDescriptor.fromAssetImage(ImageConfiguration(size: Size(12, 12)),
'assets/images/car-icon.png')
.then((d) {
customIcon = d;
});
final nearbyCarsLocation = [
LatLng(24.9286825, 67.0403249),
LatLng(24.985577, 67.0661056), //24.9294892,67.0391903,18.73z
];
void _getNearByCars() {
for (var i = 0; i < nearbyCarsLocation.length; i++) {
var now = new DateTime.now().millisecondsSinceEpoch;
_markers.add(Marker(
markerId: MarkerId(nearbyCarsLocation[i].toString() + now.toString()),
position: nearbyCarsLocation[i],
// infoWindow: InfoWindow(title: address, snippet: "go here"),
icon: customIcon ));
}
notifyListeners();
}
Hope this will help in getting custom nearby localities

I have a flutter function to add markers to GoogleMaps with text from the Firestore database

I am able to add the markers to the map but when I try to add the name of the place in the infowindow, only one name appears on all the infowindows. My intention is to have a different name for each infowindow.
Here's the code for the function
_handleTapOrig() {
LatLng tappedPoint;
setState(() {
FirebaseFirestore.instance.collection('bus_stages').get().then((value) {
if (value.docs.isNotEmpty) {
for (int i = 0; i < value.docs.length; i++) {
DocumentSnapshot snap = value.docs[i];
GeoPoint geoPoint = snap.get("location");
double mylat = geoPoint.latitude;
String jje = snap.get("stage_name");
double mylng = geoPoint.longitude;
LatLng mypoint = LatLng(mylat, mylng);
setState(() {
_mylatlng.add(LatLng(mylat, mylng)
);
});
///Add markers
myMarker = [];
_mylatlng.forEach((element) {
tappedPoint = element;
myMarker.add(Marker(
markerId: MarkerId(tappedPoint.toString()),
position: tappedPoint,
icon: myBitmapDescriptor,
/// BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueCyan),
infoWindow: InfoWindow(title: "Bus Stage ${snap.get("stage_name")}",
snippet: 'Tap Google directions button to navigate to stage'),
));
});
}
// print(_mylatlng);
}
});
// print('List of Markers: $myMarker');
});
}

How to cancel the drag event of Google map marker and take it back to its initial position in Flutter?

I am using google_maps_flutter for creating a Google map with two types of markers. When one type of marker is dragged over the other, I want to remove the dragged marker and then perform a function. I am able to do this.
But, in case the dragged marker is dropped in a wrong position, then I want to place the marker back to its original position. I couldn't find any event or method to achieve this. How can this be done?
Here is my code for adding markers:
markers.add(
Marker(
markerId: packageMarkerId,
draggable: true,
icon: _unassignedOrderMarkerIcon,
onTap: () {
print('marker tapped');
},
position: LatLng(coordinates.latitude, coordinates.longitude),
onDragEnd: (LatLng latLng) {
double newLat =
double.parse(latLng.latitude.toStringAsFixed(1));
double newLong =
double.parse(latLng.longitude.toStringAsFixed(1));
for (var user in usersDocuments) {
Map<String, dynamic> userLocation =
user.data['user_location'];
if (userLocation != null) {
if (newLat == userLocation['latitude'] &&
newLong == userLocation['longitude']) {
print('Equal coords: $latLng');
markers.removeWhere((element) {
print('Marker removed!');
return element.markerId == packageMarkerId;
});
setState(() {
_markers = markers;
});
return;
} else {
print('Unequal coords, not merged!');
print(userLocation['latitude']);
print(userLocation['longitude']);
return;
}
}
}
},
),
);