I'm a total noob with flutter and I'm trying to create an app that shows me some markers on a map pointing the location of the soccer fields and only this.
enter image description here
Currently i have the google map marks all the places nearby. I did this using the google Nearvy places API. So I need it to only mark the nearby soccer fields, but this option does not appear in the type section.
This is the code that I use to use the google api. As u seen in the url, the word soccer in type does not work.
Future<dynamic> getPlaceDetails(LatLng coords, int radius) async {
var lat = coords.latitude;
var lng = coords.longitude;
final String url =
'https://maps.googleapis.com/maps/api/place/nearbysearch/json?&location=$lat,$lng&radius=$radius&type=soccer&key=$key';
var response = await http.get(Uri.parse(url));
var json = convert.jsonDecode(response.body);
return json;
}
This is the method I use to mark the nearvy places
void maracaCanchas() {
if (_debounce?.isActive ?? false) _debounce?.cancel();
_debounce = Timer(Duration(seconds: 2), () async {
var placesResult =
await MapServices().getPlaceDetails(tappedPoint, radiusValue.toInt());
List<dynamic> placesWithin = placesResult['results'] as List;
allFavoritePlaces = placesWithin;
tokenKey = placesResult['next_page_token'] ?? 'none';
_markers = {};
placesWithin.forEach((element) {
_setNearMarker(
LatLng(element['geometry']['location']['lat'],
element['geometry']['location']['lng']),
element['name'],
element['types'],
element['business_status'] ?? 'not available',
);
});
_markersDupe = _markers;
pressedNear = true;
_setLocationMarker();
});
}
Please help me.
I am trying to mark only soccer fields on the map, but it brings me all the places
Related
This is all my code. I want it to be able to search for places from lat , lng , and if lat,lng is not there, it will search for places from names. But now it's like when searching for a place from the name. In the part where the name is converted to lat,lng it's correct but my marker appears in the middle of the sea
LatLng centerMap = LatLng(13.730452094709594, 100.64180575311175);
#override
void initState() {
findLocation();
super.initState();
}
void findLocation() async {
var lat = double.tryParse(searchitems[0].address![widget.index].latitude.toString());
var lng = double.tryParse(searchitems[0].address![widget.index].longitude.toString());
if (lat != null && lng != null) {
centerMap = LatLng(lat, lng);
} else {
var name = searchitems[0].name;
var addr = '${searchitems[0].address![widget.index].addr1!}, ${searchitems[0].address![widget.index].thanon!}, ${searchitems[0].address![widget.index].tambon!}, ${searchitems[0].address![widget.index].province!}';
var addresses = await Geocoder.local.findAddressesFromQuery(addr);
var first = addresses.first;
centerMap = LatLng(first.coordinates.latitude!, first.coordinates.longitude!);
print("Location not found, searching for name: $name and address: $addr");
}
print("map:$centerMap");
}
GoogleMap(
initialCameraPosition: CameraPosition(
target: centerMap,
zoom: 16.0,
),
You can add a controller in Google maps, then when you call the API and get new lat long, you can animate camera to that position like this:
Future<void> _goToNewPosition() async {
final GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newCameraPosition(_kLake));
}
There's also an example on the official package, you can check it out by this link
it's my code
class TrackingManager {
Location locate = new Location();
Future<Map<String, double>> trackOn() async {
LocationData getlocationdata = await locate.getLocation();
Map<String, double> locationdata = {};
locationdata['latitude'] = getlocationdata.latitude ?? 0;
locationdata['longitude'] = getlocationdata.longitude ?? 0;
return locationdata;
}
}
if controller(user) call TrackingManager and initialize object,
and use trackOn so Stores the location information of the current user.
class LocateApiRequest {
final _networkManager = NetworkManager();
final _trackingManager = TrackingManager();
Future transmit(String accessToken) async {
final locationdata = await _trackingManager.trackOn();
final response = await _networkManager
.send(ApiRequestFactory.transmit(locationdata, accessToken));
final statusCode = response.statusCode;
if (statusCode == 200) {
final responseBody = jsonDecode(response.body);
return responseBody;
}
throw statusCode;
}
}
and Send the data to the server by requesting a post
But this action is carried out only once.
Starting with when a user clicks a specific button, I want to do this on the server with a regular time (background, foreground status is not important)
how can i solve it?I've thought about using a repeat statement, but this doesn't seem reasonable
using location callback
https://pub.dev/packages/location
location.onLocationChanged.listen((LocationData currentLocation) {
// call network api
// Use current location
});
i have a list of volumes that looks like this
['9v9JXgmM3F0C','RoAwAAAAYAAJ','RYAwAAAAYAAJ']
i have a ready funtion that sends Individual volumes and retruns a Map.
Future<BookIdVolume> getBooksByVolume(volume) async {
var searchUrl = 'https://www.googleapis.com/books/v1/volumes/$volume';
var response = await http.get(searchUrl);
var responseBody = jsonDecode(response.body);
return BookIdVolume.fromJson(responseBody);
}
Im trying to create a method to store each of volumes in a list and retrun it.
I have tryed using loops for and forEach but it keeps retruning either [] or null
im i doing somthing wong ? is thier a better better way to do it ?
I'm guessing you're getting null back because you're not building the url properly for each volume. Try this.
final volumeList = ['9v9JXgmM3F0C', 'RoAwAAAAYAAJ', 'RYAwAAAAYAAJ'];
final baseUrl = 'https://www.googleapis.com/books/v1/volumes/';
List<BookIdVolume> bookList = [];
void buildBookList() async {
for (String volume in volumeList) {
final url = '$baseUrl$volume';
final book = await getBooksByVolume(url);
bookList.add(book);
}
}
Then you remove the first line from the getBooksByVolume function because you're already sending the full url.
Future<BookIdVolume> getBooksByVolume(url) async {
var response = await http.get(url);
var responseBody = jsonDecode(response.body);
return BookIdVolume.fromJson(responseBody);
}
I am using this package to retrieve device's contacts. The lib retrieve 427 contacts and I want to loop the whole list so that I can create another list and send it to the back-end. The problem is looping does not work this the function return before looping is completed.
Here the function I use:
Future<QueryResult> uploadContacts() async {
final List<Contact> rawContacts =
(await ContactsService.getContacts(withThumbnails: false)).toList();
List<ContactInput> contactsListInput;
print('contactsListInput length: ${rawContacts.length}');
rawContacts.forEach((contact) {
print('contact: $contact'); //PRINTED JUST ONCE
//Contact can have more than 1 number. We need them all
contact.phones.forEach((phone) {
final contactInput =
ContactInput(name: contact.displayName, phone: phone.value);
contactsListInput.add(contactInput);
});
});
print('contactsListInput length: ${contactsListInput.length}'); //NEVER PRINT ANYTHING
final ContactsListInput input =
ContactsListInput(contacts: contactsListInput);
final MutationOptions _options = MutationOptions(
document: SyncContactsMutation().document,
variables: SyncContactsArguments(input: input).toJson());
return client.mutate(_options);
}
I have also tried using for loop and the same thing happened.
for (int i = 0; i < rawContacts.length; i++) {
final contact = rawContacts[i];
final contactInput =
ContactInput(name: contact.displayName, phone: contact.phones.first.value);
contactsListInput.add(contactInput);
}
print('contactsListInput length: ${contactsListInput.length}'); //NEVER CALLED
And I also tried Future.forEach
await Future.forEach(rawContacts, (contact) async {
print('contact: $contact');
//Since contact can have more than one number we loop them too.
await Future.forEach(contact.phones, (phone) async {
final contactInput =
ContactInput(name: contact.displayName, phone: phone.value);
contactsListInput.add(contactInput);
});
});
How to fix this? Any help will be much appreciated.
I have fixed it as
Future<QueryResult> uploadContacts() async {
final Iterable<Contact> rawContacts =
(await ContactsService.getContacts(withThumbnails: false));
final Iterable<ContactInput> contacts = rawContacts.expand((contact) => contact.phones.map(
(phone) =>
ContactInput(name: contact.displayName, phone: phone.value)));
final input = ContactsListInput(contacts: contacts);
final MutationOptions _options = MutationOptions(
document: SyncContactsMutation().document,
variables: SyncContactsArguments(input: input).toJson());
return client.mutate(_options);
}
Credit goes to #pskink and #loganrussell48
You should use it as a dynamic type object. Try something like this:
(event.snapshot.value as dynamic).forEach()
Try and see if it works.
I have this code trying to query some data from Firestore using GeoFlutterFire, but for the sake of efficiency I want to fetch the list of ids only once, then use it to fetch the rest of the data from Firebase Database.
This is the code in question:
class _StartScreenState extends State<StartScreen> {
List ids = ['abc'];
#override
void initState() {
super.initState();
print('ids ${ids}');
}
_initState() async {
Firestore _firestore = Firestore.instance;
List ids1 = [];
Geoflutterfire geo = Geoflutterfire();
var location = new Location();
var pos = await location.getLocation();
GeoFirePoint center = geo.point(latitude: pos.latitude.toDouble(), longitude: pos.longitude.toDouble());
var collectionReference = _firestore.collection('locations');
var geoRef = geo.collection(collectionRef: collectionReference);
return ids1.add(geoRef.within(center: center, radius: 50, field: 'position', strictMode: true).first.then((value) {
value.map((doc) {
if (doc.data.isNotEmpty) {
print('doooc id here ${doc['id']}');
ids1.add(doc['id']);
print(ids1);
}
}).toList();
setState(() {
ids = ids1;
print('setting state to ids ids print: ${ids.}');
});
}));
}
Like I said, my intent is to fetch the Ids and once I have the list check if there's some related data in Firebase, but I'm not sure this is the way I should do it and there's something that I don't know how to awoid; When I print the list I get the following result:
setting state to ids ids print: [Instance of 'Future',
3esdWesqrTD_123_3dssds3, sQWdsda23dsad_da21]
Can anyone tell me why I have this Instance of 'Future' in my List and how can avoid it, please?
I have not tried to run your code, but I suspect the issue starts with the statement
return ids1.add(geoRef.within(center: center, radius: 50, field: 'position', strictMode: true).first.then((value) {
As you can see, you are adding something ids1.add(...) that looks like it needs to await: geoRef.within(...).first.(...). I don't find the ids1.add(...) call needed in the return statement. Try removing it, and see how it goes.