Flutter google map custom marker with gesture detector - flutter

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

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

How to update marker position google maps 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;
});
}
});

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');
});
}

flutter How to get markers from API and show on map

I make a simple app in flutter to get markers from API and draw them on Google Map.
I make a model with Location name and I have get markers information from the API and added them to the list of markers.
But when I run my app, no markers shown on map.
How can I solve this problem?
My function That get markers from API :
Future<List<Location>> getLocations() async {
try {
var url = 'http://10.0.2.2/Track_App/locations.php';
final resp = await http.get(url);
final responsebody = jsonDecode(resp.body);
return responsebody; //this return a list
} catch (e) {
return [];
}
}
List<Marker> allMarkers = [];
loadLocations() async {
List<Location> locations;
locations = [];
locations = await getLocations(); //we store the response in a list
for (var i = 0; i < locations.length; i++) {
LatLng latlng;
latlng = LatLng(
double.parse(locations[i].locX),
double.parse(locations[i].locY),
);
allMarkers.add(
Marker(
markerId: MarkerId(locations[i].locId.toString()),
position: latlng,
),
);
}
setState(() {});
}
Google Map Code :
FutureBuilder(
future: loadLocations(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
return GoogleMap(
mapType: MapType.normal,
initialCameraPosition: _kGooglePlex,
markers: snapshot.data,
);
},
),
JSON data from API :
[
{
loc_id: "1 ",
loc_x: "15.392567",
loc_y: "44.278188"
},
{
loc_id: "2 ",
loc_x: "15.391717",
loc_y: "44.278019"
}
]
My Model :
class Location {
Location({
this.locId,
this.locX,
this.locY,
this.locInfo,
this.locSpd,
this.locDate,
});
String locId;
String locX;
String locY;
String locInfo;
String locSpd;
String locDate;
factory Location.fromJson(Map<String, dynamic> json) => Location(
locId: json['loc_id'],
locX: json['loc_x'],
locY: json['loc_y'],
locInfo: json['loc_info'],
locSpd: json['loc_spd'],
locDate: json['loc_date'],
);
Map<String, dynamic> toJson() => {
'loc_id': locId,
'loc_x': locX,
'loc_y': locY,
'loc_info': locInfo,
'loc_spd': locSpd,
'loc_date': locDate,
};
}
Map<MarkerId, Marker> markers = <MarkerId, Marker>{};
Whenever, you want to add maker here, create a new Marker and add to State
Marker marker = Marker(...)
setState(() {
markers[markerId] = marker;
});
And your build function would just be like this
child: GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: const CameraPosition(
target: LatLng(-33.852, 151.211),
zoom: 11.0,
),
markers: Set<Marker>.of(markers.values),
),
this code work for me just change your location listner
Future<Offre> location_client() async{
var _loc = await _location.getLocation();
setState(() {
client_lat = _loc.client.lat;
client_lng = _loc.client.lng;
print("test test"+_loc.client.lat.toString()+','+_loc.client.lng.toString());
LatLng latlng = LatLng(client_lat,client_lng);
setState(() {
_markers.add(Marker(
markerId: const MarkerId("home"),
position: latlng,
draggable: false,
zIndex: 2,
flat: true,
anchor: const Offset(0.5, 0.5),
icon: BitmapDescriptor.defaultMarker));
});
});
}

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;
}
}
}
},
),
);