Направления Api не принимает отрицательные значения для координат? флаттер - PullRequest
0 голосов
/ 13 марта 2020

Я отправляю запрос направления API, и я столкнулся с этой проблемой. С координатами flutter: start location is :latitude 37.33101308, longitude -122.03065487 и end location is :latitude 37.33097983, longitude -122.03063943 символ - создает проблему.

При отправке полученного запроса

http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&v=bicycle&fast=0&layer=mapnik&flat=37.33101308&flon=-122.03065487&tlat=37.33097983&tlon=-122.03063943&geometry=1&instructions=1&lang=it

Я получаю ошибку, которую пока не могу понять:

[ VERBOSE-2: ui_dart_state. cc (157)] Необработанное исключение: FormatException: неожиданный символ (в символе 1) ^

0 _ChunkedJsonParser.fail (dart: convert-patch / convert_patch.dart: 1394: 5 )

1 _ChunkedJsonParser.parseNumber (dart: convert-patch / convert_patch.dart: 1261: 9)

2 _ChunkedJsonParser.parse (дарт: convert-patch / convert_patch.dart: 926: 22 )

3 _parse Json (дартс: convert-patch / convert_patch.dart: 31: 10)

4 JsonDecoder.convert (дарт: convert / json .dart: 495: 36)

5 JsonCode c .decode (дарт: конвертировать / json .дарт: 153: 41)

6 jsonDecode (дарт: конвертировать / json .дарт: 96 : 10)

7 DirectionsRepository.postRequest (пакет: fixit_cloud_biking / directions / directions_repository.dart: 39: 26)

8 DirectionsBlo c .getDirections (пакет: fixit_clou d_biking / directions / directions_blo c .dart: 46: 12)

9 _AsyncStarStreamController.runBody (dart: asyn c -patch / async_patch.dart: 155: 5)

10 _rootRun (dart: async / zone.dart: 1122: 3 <…>

Это из-за проблемы форматирования json или это означает, что www.yournavigation.org/api не принимает отрицательные значения координат ?

Эта ошибка не возникает, если отправленный запрос имеет положительные координаты, как это

'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&v=bicycle&fast=0&layer=mapnik&flat=44.5018645003438&flon=11.340018709036542&tlat=44.502138&tlon=11.340402&geometry=1&instructions=1&lang=it'

Просто для тестирования я попытался сделать их положительными координатами с .abs(). но, конечно, результаты - неправильное местоположение на карте. Есть ли другая система координат, которая имеет все положительные значения?

Большое спасибо за вашу помощь.

Это класс, из которого я отправляю запрос:

import 'package:http/http.dart';
import 'package:latlong/latlong.dart';
import 'dart:convert' as convert;
import 'dart:math';

class DirectionsRepository {
  Future<List<LatLng>> postRequest(LatLng start, LatLng end) async {
    print('postRequest() called');
    print(
        'start location is :latitude ${start.latitude}, longitude ${start.longitude}');
    print(
        'end location is :latitude ${end.latitude}, longitude ${end.longitude}');

    // NORMAL NEGATIVE LONGITUDE THROWS = API ERROR:
    // format error [VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: FormatException: Unexpected character (at character 1)
    String flat = (start.latitude).toString();
    String flon = (start.longitude).toString();
    String tlat = (end.latitude).toString();
    String tlon = (end.longitude).toString();

    // ALL POSITIVE VALUES DON'T THROW AN ERROR BUT IS WRONG PLACE
//    String flat = (start.latitude).abs().toString();
//    String flon = (start.longitude).abs().toString();

//    String tlat = (end.latitude).abs().toString();
//    String tlon = (end.longitude).abs().toString();

    final request =
        'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&v=bicycle&fast=0&layer=mapnik&flat=$flat&flon=$flon&tlat=$tlat&tlon=$tlon&geometry=1&instructions=1&lang=it';

    print('final request is $request');
    // working properly
//    final request =
//        'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&v=bicycle&fast=0&layer=mapnik&flat=44.5018645003438&flon=11.340018709036542&tlat=44.502138&tlon=11.340402&geometry=1&instructions=1&lang=it';

    // Await the http get response, then decode the json-formatted response.
    var response = await get(request);
    if (response.statusCode == 200) {
      var jsonResponse = convert.jsonDecode(response.body);
      print('${jsonResponse.runtimeType} : $jsonResponse');
      List<dynamic> coordinates = jsonResponse['coordinates'];
      print('coordinates are : $coordinates');
      print('coordinates are: ${coordinates.length}');
      Map<String, dynamic> properties = jsonResponse['properties'];
//      print('properties are $properties');
      String distance = properties['distance'];
      print('Route is $distance Km long.');
      String instructions = properties['description'];
      print('instructions are $instructions');

      List<LatLng> suggestedRoute = [];
      for (int i = 0; i < (coordinates.length); i++) {
        dynamic coordinate = coordinates[i];
        LatLng position = LatLng(coordinate[1], coordinate[0]);
        suggestedRoute.add(position);
        print('position is $position');
        print(i);
      }
      print('postRequest() suggestedRoute is $suggestedRoute');
      return suggestedRoute;
    } else {
      print(
          'postRequest() Request failed with status: ${response.statusCode}.');
    }
  }
}

1 Ответ

0 голосов
/ 14 марта 2020

После нескольких попыток я решил проблему с сервером направления API. Итак, запрос в порядке, но декодирование json метода просто не удается, потому что он получает код состояния ответа 242, который проходит проверку, но не проходит, поскольку тело ответа не соответствует тому, что обрабатывается в методе.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...