Reputation: 303
Location class is the responsible for getting the longitude and latitude. getData() method from the Loading_screen class is the responsible for calling the api to get weather data. The problem is when I pass the longitude and latitude values to the url of api, it returned error 400. Workaround is to hardcode the longitude and latitude and it successfully retrieved api data. I can't figure why passing longitude and latitude values to api call doesn't work
Location
import 'package:geolocator/geolocator.dart';
import 'package:http/http.dart' as http;
class Location{
double longitude;
double latitude;
Future<void> getCurrentLocation() async{
try{
Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
longitude = position.longitude;
latitude = position.latitude;
print('Longitude: $longitude \n' +
'Latitude: $latitude');
}catch(e){
print(e);
}
}
}
Loading_screen class
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:clima/location.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class LoadingScreen extends StatefulWidget {
@override
_LoadingScreenState createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
var apiKey = 'secret';
double lat, lon;
@override
void initState() {
getLocation();
}
void getData() async{
var url = 'http://api.openweathermap.org/data/2.5/weather?lat=${lat}&${lon}&appid=$apiKey';
//var url = 'http://api.openweathermap.org/data/2.5/weather?lat=14.6102473&121.0043158&appid=secret';
//var url = 'http://api.openweathermap.org/data/2.5/weather?lat=14.6102473&lon=121.0043158&appid=secret';
var request = await http.get(url);
if(request.statusCode == 200){
String data = request.body.toString();
var city = jsonDecode(data)['name'];
var description = jsonDecode(data)['weather'][0]['description'];
print('Welcome to $city city!');
print('Weather: $description');
}else{
print(request.statusCode);
print('Latitude is: $lat *** Longitude is: $lon'); // this prints longitude and latitude values
print('request $url'); // when I entered the url in postman, I'm getting the same error 400
}
}
void getLocation() async{
Location location = new Location();
await location.getCurrentLocation();
lat = location.latitude;
lon = location.longitude;
getData();
}
@override
Widget build(BuildContext context) {
return Scaffold();
}
}
Upvotes: 1
Views: 566
Reputation: 99
Change that;
var url = 'http://api.openweathermap.org/data/2.5/weather?lat=${lat}&${lon}&appid=$apiKey';
with this;
var url = 'http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=$apiKey';
Upvotes: 2
Reputation: 107121
You are missing the parameter name lon
in your url.
Instead of:
var url = 'http://api.openweathermap.org/data/2.5/weather?lat=${lat}&${lon}&appid=$apiKey';
Write:
var url = 'http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=$apiKey';
Upvotes: 2