Geolocator position does not appear in the console and there is no errors also I have tried to get the longitude and latitude using position.longitude separately but nothing changes , the problem is with this line but I am not able to determine it : Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
and here is the code:
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
class LoadingScreen extends StatefulWidget {
#override
_LoadingScreenState createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
void getLocation() async{
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
print(position);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
onPressed: () {
getLocation();
// _determinePosition();
//Get the current location
},
child: Text('Get Location'),
),
),
);
}
}
Add following permission in AndroidManifest.xml for accessing location.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Check for service enable or not.
bool servicestatus = await Geolocator.isLocationServiceEnabled();
if(servicestatus){
print("GPS service is enabled");
}else{
print("GPS service is disabled.");
}
Now try to fetch location details.
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
print(position.longitude); //Output: 80.24599079
print(position.latitude); //Output: 29.6593457
Related
The print works perfectly well when it the getLocation function is called inside the onPressed of elevated button.
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
void main(List<String> args) {
runApp(const LoadingScreen());
}
class LoadingScreen extends StatefulWidget {
const LoadingScreen({super.key});
#override
State<LoadingScreen> createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
void getLocation() async {
LocationPermission permission;
permission = await Geolocator.checkPermission();
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
//nothing
}
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.low);
print(position);
}
#override
void initState() {
super.initState();
getLocation();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: ElevatedButton(
onPressed: (() {
getLocation();
}),
child: const Text(''),
),
),
],
),
),
);
}
}
But when I try to call the same getLocation function inside initstate, the print function 'prints' nothing inside the console.
P.S. I am using VSCode and emulator is Genymotion.
I want to show weather name on dialog box ,But when i Click first time on button data is not loading only show dialog box after that when i click second time then my data is loading.
I want to show weather name on dialog box ,But when i Click first time on button data is not loading only show dialog box after that when i click second time then my data is loading.
I want to show my data on first click please help how to do this.
This is my code
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:weather/weather.dart';
void main() => runApp(MyAppp());
class MyAppp extends StatefulWidget {
const MyAppp({ Key? key }) : super(key: key);
#override
_MyApppState createState() => _MyApppState();
}
class _MyApppState extends State<MyAppp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home:ButtonPage()
);
}
}
class ButtonPage extends StatefulWidget {
const ButtonPage({ Key? key }) : super(key: key);
#override
_ButtonPageState createState() => _ButtonPageState();
}
class _ButtonPageState extends State<ButtonPage> {
// passing this to latitude and longitude strings
String key = '856822fd8e22db5e1ba48c0e7d69844a';
late WeatherFactory ws;
List<Weather> _data = [];
double? lat, lon;
#override
void initState() {
super.initState();
ws = new WeatherFactory(key);
}
void getCurrentLocation() async {
var position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
var lat = position.latitude;
var long = position.longitude;
print(lat);
print(long);
queryWeather( lat,long) ;
}
queryWeather(var lat,var long) async {
print("Data: "+_data.toString());
/// Removes keyboard
FocusScope.of(context).requestFocus(FocusNode());
Weather weather = await ws.currentWeatherByLocation(lat, long);
setState(() {
_data = [weather];
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: RaisedButton(onPressed: () {
getCurrentLocation();
showDialog<void>(
context: context,
// barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return Dialog(
child: Center(
child: ListView.builder(
itemCount: _data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text("${_data[index].areaName}"),
);
},
),
),
);
},
);
},
child: Text("Button"),),),
);
}
}
I am using this permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
weather: ^2.0.1
geolocator: ^7.4.0
url_launcher: ^6.0.9
Since getCurrentLocation is async, you have to mark your onPressed as async and await the result of getCurrentLocation:
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: RaisedButton(onPressed: () async {
await getCurrentLocation();
...
Also you have to await queryWeather call as well:
void getCurrentLocation() async {
var position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
var lat = position.latitude;
var long = position.longitude;
await queryWeather( lat,long) ;
}
Flutter how to get latitude, longitude using geolocator package?
Already gave permissions both android and ios, downloaded package using pubspec.yaml. I don't understand why can't print longitude and latitude to console? tried write print(position), print(position.longitude()), print(position.latitue()).
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
class LoadingScreen extends StatefulWidget {
#override
_LoadingScreenState createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
void getLocation() async {
print('Printing text before getCurrentLocation()');
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
print(position);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
color: Colors.red,
onPressed: () {
getLocation();
},
child: Text('Get Location'),
),
),
);
}
} ```
It should be position.latitude or position.longitude. You've used position.longitude() & position.latitude(), which is incorrect.
Also, you need to add async-await for onPressed callback. I'm assuming that you've added permissions in manifest & granted the necessary permissions as well.
Method
void getLocation() async {
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
print(position.latitude);
print(position.longitude);
}
Widget
RaisedButton(
color: Colors.red,
onPressed: () async {
await getLocation();
},
child: Text('Get Location'),
),
Here is my code in a loading_screen.dart file. I've clearly mentioned to print my position and even called the method in onpressed. Still no response from it.
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
class LoadingScreen extends StatefulWidget {
#override
_LoadingScreenState createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
void getLocation() async{
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
print(position);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
onPressed: () {
getLocation();
},
child: Text('Get Location'),
),
),
);
}
}
There are few steps missing from your implementation.
First you need to check for permission, if permission is allowed, get location else ask for permission.
You also need to add permission in you manifest for android and in info.plist for ios
sample code :-
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Test(),
);
}
}
class Test extends StatefulWidget{
#override
_Test createState() => _Test();
}
class _Test extends State<Test>{
void getLocation() async{
LocationPermission permission = await Geolocator.checkPermission();
if(permission == LocationPermission.always || permission == LocationPermission.whileInUse) {
printLocation();
}else{
requestPermission();
}
}
requestPermission() async{
LocationPermission permission = await Geolocator.requestPermission();
if(permission == LocationPermission.always || permission == LocationPermission.whileInUse) {
printLocation();
}else{
requestPermission();
}
}
printLocation() async{
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low, timeLimit: Duration(seconds: 10));
print(position);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
onPressed: () {
getLocation();
},
child: Text('Get Location'),
),
),
);
}
}
I'm using the geolocator plugin to access the user's location but it seems like it does not work, cause when I run my code I get the error on message.
I have done all the geolocation configuration, but I have the problem.
Adding the Geolocator plugin(pubspec.yaml)
dependencies:
flutter:
sdk: flutter
geolocator: ^5.1.3
For android, head on over to your AndroidManifest.xml and add either of these permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Source code for getting address
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:geolocator/geolocator.dart';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
Position _currentPosition;
String _currentAddress;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Location"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
if (_currentPosition != null) Text(_currentAddress),
FlatButton(
child: Text("Get location"),
onPressed: () {
_getCurrentLocation();
},
),
],
),
),
);
}
_getCurrentLocation() {
geolocator
.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) {
setState(() {
_currentPosition = position;
});
_getAddressFromLatLng();
}).catchError((e) {
print(e);
});
}
_getAddressFromLatLng() async {
try {
List<Placemark> p = await geolocator.placemarkFromCoordinates(
_currentPosition.latitude, _currentPosition.longitude);
Placemark place = p[0];
setState(() {
_currentAddress =
"${place.locality}, ${place.postalCode}, ${place.country}";
});
} catch (e) {
print(e);
}
}
}
The problem I get when I run my code is here.
Try flutter clean on terminal and then run the app again, You can also use location plugin instead of Geolocator, to get the user's location