Flutter : polyline이 나오지 않는 문제 해결 방법

koeyhoyh·2022년 7월 29일
2

App_Flutter

목록 보기
13/19

Flutter : flutter_polyline_points package https://pub.dev/packages/flutter_polyline_points/example
참고 :
https://medium.com/flutter-community/drawing-route-lines-on-google-maps-between-two-locations-in-flutter-4d351733ccbe


패키지를 이용한 polyline 그리기의 해결방법은 결국 찾지 못했으며,
패키지를 이용하지 않는 방법을 이용해 해결했습니다.


만든 변수

  Set<Polyline> _polylines = Set<Polyline>();
  PolylinePoints polylinePoints = PolylinePoints();

googleMap의 인자 onMapCreated

onMapCreated: (GoogleMapController controller) {
          myController.complete(controller);
          initPolyline();
          initMarker();
        },

DB를 참조해 polyline을 만드는 함수
(initState에서 한 번 실행시켜줄 함수이다.)
(추가는 별도)

  initPolyline() async {
    var locationList = await DBHelper().getAllLocation();
    if (locationList.isEmpty) return;
    if (locationList.length < 2) return;
    for (int i = 0; i < locationList.length - 1; i++) {
      List<LatLng> polylineCoordinates = [];
      PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
        '$androidgoogleMapApiKey',
        PointLatLng(locationList[i].latitude, locationList[i].longitude),
        PointLatLng(
            locationList[i + 1].latitude, locationList[i + 1].longitude),
      );
      if (result.points.isNotEmpty) {
        // loop through all PointLatLng points and convert them
        // to a list of LatLng, required by the Polyline
        result.points.forEach((PointLatLng point) {
          polylineCoordinates.add(LatLng(point.latitude, point.longitude));
        });
      }
      setState(() {
        _polylines.add(Polyline(
            width: 10,
            polylineId: PolylineId(polylineidx.toString()),
            color: Color.fromARGB(255, 40, 122, 198),
            points: polylineCoordinates));
        polylineidx++;
      });
    }
  }

의심되는 부분

  1. polylineCoordinates 에 위도와 경도가 2개 들어가지 않았다.

console에 정보를 뛰워보도록 해보니

if (result.points.isNotEmpty)
result.points.forEach((PointLatLng point) {
...}

해당 코드가 실행되지 않고 있었다.
result의 point가 비어있다는 뜻이다.

추가적으로 PolylinePoints, polylineResult 에 대해 찾아보고, 내 코드가 어떻게 실행되고 있는지 보았다.
https://pub.dev/documentation/flutter_polyline_points/latest/flutter_polyline_points/PolylinePoints-class.html

result는 getRouteBetweenCoordinates 메소드를 통해 PolylineResult type의 객체를 생성한다.

polylineResult 는 위치 정보를 나타내는 배열인 points를 가지고 있고
api가 잘 연결되어있는지를 확인하는 status,
error_message를 표기할 때 사용할 errorMessage 속성을 가지고 있다.
이 정보들을 다 확인해보았다.

위치 정보는 잘 들어가고 있었지만, apis status가 DENIED로 되어 있었다.
api key에 안드로이드로 제한한 키를 넣었던 것이 화근이었던 것 같다.

올바른 제한을 가진 api key를 넣어 생성해보았지만 이번에는 ZERO_RESULTS 라는 상태가 나왔다.

구글 맵 api에서 ZERO_RESULTS란 api는 잘 동작하지만 api 결과를 가져오는데 추가적으로 필요한 key 값들을 넣어주지 않아 발생하는 에러이다.

googlemap을 이용한 polyline_flutter 패키지는 한국에서 지원하지 않는다고 한다.


위치만 표기해주면 경로를 자동 표기해주는 방법이 이렇게 어렵지 않을 것 같은데... 하고 다른 방법을 찾아보니 패키지를 사용하지 않고도 polyline을 그릴 수 있는 쉬운 방법을 찾았다.

바로, 기본 Polyline 생성자를 사용하는 방법이다.

  initPolyline() async {
    var locationList = await DBHelper().getAllLocation();
    List<LatLng> loc = [];
    if (locationList.isEmpty) return;
    if (locationList.length < 2) return;
    for (int i = 0; i < locationList.length - 1; i++) {
      loc.add(LatLng(locationList[i].latitude, locationList[i].longitude));
    }
    _polylines.add(Polyline(
      polylineId: PolylineId(polylineidx.toString()),
      points: loc,
      color: Colors.lightBlue,
    ));
  }

심지어 코드 수도 많이 줄어들었다.
위치만 LatLng 배열로 만들어놓고 기본 Polyline 생성자를 이용해
points 속성에 위치정보만 넣어주면 해결이다.

polyline이 잘 출력되는 모습을 볼 수 있다.


잘못된 정보가 있거나, 다른 방법이 있다면 이메일이나 댓글 부탁드립니다 : )

profile
내가 만들어낸 것들로 세계에 많은 가치를 창출해내고 싶어요.

2개의 댓글

comment-user-thumbnail
2022년 11월 5일

이렇게 처리하면 그냥 직선이 그려질 뿐 제대로 된 경로가 아닙니다. 두 지점 사이의 경로, 그러니까 사람이 갈 수 있는 길을 표기 하기 위해서 폴리라인을 그리는게 일반적일텐데, 이렇게 처리하면 벽 뚫고 바다 건너고 화산도 가로지르는 경로가 나옵니다.

1개의 답글