I am currently working on an app that uses google places autocomplete to find addresses around the world. I have implemented it in the following way:
Position currentPosition;
var placeId, address;
double lat, lng;
getCurrentLocation(){
final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
geolocator
.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position){
setState(() {
currentPosition = position;
});
}).catchError((e){
print(e);
});
}
Future<Null> displayPrediction(Prediction p) async {
if (p != null) {
PlacesDetailsResponse detail = await _places.getDetailsByPlaceId(p.placeId);
placeId = p.placeId;
lat = detail.result.geometry.location.lat;
lng = detail.result.geometry.location.lng;
address = await Geocoder.local.findAddressesFromQuery(p.description);
}
}
onPressed: () async {
print(currentPosition.latitude);
print(currentPosition.longitude);
Prediction prediction = await PlacesAutocomplete.show(
context: context,
apiKey: googleApiKey,
location: Location(currentPosition.latitude, currentPosition.longitude),
radius: 100000000,
mode: Mode.overlay,
language: "en",
);
However, whenever I type something into the search bar, I do not receive any autocompleted results and I am not sure why (image attached). If it makes any difference, I am using the iOS simulator. I haven't yet tested on Android. Any help would be much appreciated.
Related
i have a problem with google maps on flutter app, im trying to animate markers iterating marker list with the following method.
Future<void> _iteratePoints() async {
CameraUpdate zoom = CameraUpdate.zoomTo(14);
controller.animateCamera(zoom);
for (final value in listIds) {
await Future.delayed(Duration(seconds: 3));
updatePosition(value);
updateDetailPosition(value);
}
}
Future<void> updateDetailPosition(MarkerAndDetails markerId) async {
print(markerId.toJson().toString());
this.setState(() {
currentlySelectedPin = markerId;
});
}
Future<void> updatePosition(MarkerGlobal markerId) async {
final Marker marker = markers[markerId.markerId];
final LatLng current = marker.position;
var newPosition = CameraPosition(target: LatLng(current.latitude, current.longitude), zoom: 12);
CameraUpdate update = CameraUpdate.newCameraPosition(newPosition);
// CameraUpdate zoom = CameraUpdate.zoomTo(16);
// controller.animateCamera(update);
controller.showMarkerInfoWindow(markerId.markerId);
}
But when im trying on iphone... i have next error:
Unhandled Exception: Concurrent modification during iteration: Instance(length:798) of '_GrowableList'.
I hope someone can help me.
I have a problem with the query with the condition isNotEqualTo does not work and does not show the values checked from the condition, note that I tried the condition isNotEqualTo and it worked
What is the problem
_setStream() async {
var pos = await location.getLocation();
double lat = pos.latitude!;
double lng = pos.longitude!;
var ref = await FirebaseFirestore.instance.collection('now')
.where('uid', isNotEqualTo: _user.uid).orderBy('uid');
GeoFirePoint center = geo.point(latitude: lat, longitude: lng);
stream = radius.switchMap((rad) {
var collectionReference = ref;
return geo.collection(collectionRef: collectionReference).within(
center: center, radius: rad, field: 'location', strictMode: true);
});
setState(() {
isLoading = false;
});
stream = geo.collection(collectionRef: ref).within(
center: center, radius: 2000, field: 'location', strictMode: true);
stream!.listen((List<DocumentSnapshot> documentList) {
documentList.forEach((element) {
print("from data .......element");
print(element.data());
final data = element.data() as Map<String, dynamic>;
final GeoPoint point = data['location']['geopoint'];
print("from data .......latitude");
print(point.latitude);
});
});
}
Even though NotEqual query is available in firebase, it was made available late in flutter plugin. The best option is to fetch all to a list and remove unwanted elements from the list
I used geolocator flutter package for my little app and it works perfectly with emulator, but when I try to use in my real smart phone, it doesnt work. Do you have any idea?
void getLocationData() async {
WeatherModel weatherModel = WeatherModel();
var weatherData = await weatherModel.getLocationWeather();
//print(weatherData);
var zipCode = await weatherModel.getLocationZipCode();
zipCode = zipCode.toString().substring(0, 2);
Navigator.push(context, MaterialPageRoute(builder: (context) {
return LocationScreen(
locationWeather: weatherData,
zipCode: zipCode,
);
}));
}
Future<dynamic> getLocationWeather() async {
Location location = Location();
await location.getCurrentLocation();
NetworkHelper networkHelper = NetworkHelper(
'$openWeatherMapURL?lat=${location.latitude}&lon=${location.longitude}&appid=$apiKey&units=metric');
var weatherData = await networkHelper.getData();
return weatherData;
}
Angela Yu's student? her projects need one update for optimizing and fixing little errors.
I got problems with Geolocator, it was not being used correctly, and this site helped me a lot. Then I made my own Location class with Provider and... life becomes good again.
Try use geolocator. I seems you are not using geolocator package
final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
// return true if location service is enable, false if not
bool locationServiceEnable = await geolocator.isLocationServiceEnabled();
// position instace
Position position;
// if location service enable get current position
if (locationServiceEnable) {
// await current position
position = await geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best);
// if location service is not enable get last known position
} else {
// await last known position
position = await geolocator.getLastKnownPosition(
desiredAccuracy: LocationAccuracy.best);
}
if (position != null) {
// fetch weather data with position data
}
You should add
<uses-permission android:name="android.permission.INTERNET" />
to the AndroidManifest.xml. It helps to use the internet to fetch location data in an Android device, because your app still need to get data from URL openweathermap.
using geolocator: ^7.0.1
and adding
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
to AndroidManifest.xml file
void getLocation() async {
print('getLocation');
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
print(position);
}
and using in onPressed
onPressed: () {
getLocation();
},
solves the problem.
i made an app which uses the geolocator package to check for GPS and get the location of the user, and i use the provider package to handle the state. The problem is, when the GPS is switched off, a red screen appears that says the latitude was null, i would like to implement a screen to tell the user to switch on the GPS, and update the location accordingly.
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:geolocator/geolocator.dart';
import 'package:latlong/latlong.dart';
class MapState with ChangeNotifier {
bool locationServiceActive = true;
MapController _mapController;
MapController get mapController => _mapController;
static var _initialPosition;
var _lastPosition = _initialPosition;
LatLng get initialPosition => _initialPosition;
LatLng get lastPosition => _lastPosition;
MapState(){
checkGPS();
_getUserLocation();
}
checkGPS() async{
bool conn = await Geolocator().isLocationServiceEnabled();
if(conn == false){
locationServiceActive = false;
} else {
locationServiceActive = true;
}
notifyListeners();
}
void _getUserLocation() async{
Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
print("/////////////////////////////////////////////////////////////////////////////////position");
print(position);
_initialPosition = LatLng(position.latitude, position.longitude);
notifyListeners();
}
}
update:-
i changed my _getUserLocation function to a stream, which works much better if the user switched on or off the gps (and it uses the last known location if the gps is off)... but it doesn't print the statement in the terminal if the position is null which is weird, only when there is lat and lng!!!
here is the modification i made...
void _getUserLocation() async{
Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
var geolocator = Geolocator();
var locationOptions = LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 10);
StreamSubscription<Position> positionStream = geolocator.getPositionStream(locationOptions).listen(
(Position position) {
print("/////////////////////////////////////////////////////////////////////////// position");
print(position == null ? 'Unknown' : position.latitude.toString() + ', ' + position.longitude.toString());
});
_initialPosition = LatLng(position.latitude, position.longitude);
notifyListeners();
}
If you want to notify the user about the GPS, you can use something like this
#override
void initState() {
super.initState();
initPlatformState();
location.onLocationChanged.listen((result) {
currentLocation = result;
// your code
});
});
}
void initPlatformState() async {
LocationData currentLocation;
try {
currentLocation = await location.getLocation();
error = "";
} on PlatformException catch (e) {
if (e.code == 'PERMISSION_DENIED')
error = 'Permission Denied';
else if (e.code == 'PERMISSION_DENIED_NEVER_ASK')
error =
'Permission denied - please ask the user to enable it from the app settings';
currentLocation = null;
}
setState(() {
currentLocation = currentLocation;
});
}
Here, you are listening to the location stream if enabled. In case it is not then it throws an error. The package being used here is location
Is daily limit really only 1 request or am I missing something? Sometimes I get suggestions but they disappear, on google console metrics I have 97% of 403 error. I use default following code:
Future<Null> displayPrediction(Prediction p) async {
const kGoogleApiKey = "";
GoogleMapsPlaces _places = GoogleMapsPlaces(apiKey: kGoogleApiKey);
if (p != null) {
PlacesDetailsResponse detail =
await _places.getDetailsByPlaceId(p.placeId);
var address = await Geocoder.local.findAddressesFromQuery(p.description);
// print(lat);
// print(address);
}
}
Prediction p = await PlacesAutocomplete.show(
context: context, apiKey: kGoogleApiKey);
displayPrediction(p);