How to transform a google polyline string to a Set<Polyline> in flutter?

852 Views Asked by At

I have an API that returns an encoded polyline string and I need to show the polyline on a map.

How can I trasform the String "_p~iF~ps|U_ulLnnqC_mqNvxq`@" to a Set<Polyline> ?

GoogleMap(
    mapType: MapType.normal,
    initialCameraPosition: initialPosition,
    polylines: ????,
),

I tried with google_polyline_algorithm library, but when I decode the polyline I get a List<List<num>> instead of a Set<Polyline>.

1

There are 1 best solutions below

0
Neil-NotNeo On BEST ANSWER

I have implemented like this and it worked

Plugin used:

google_maps_flutter

flutter_polyline_points

For GoogleMap:

  GoogleMap(
              mapType: MapType.normal,
              myLocationButtonEnabled: true,
              markers: markers,
              polylines: _polylines,

To get the Direction from Google Direction API

 class DirectionsRepository {
   static const String _baseUrl =
  'https://maps.googleapis.com/maps/api/directions/json?';

 final Dio _dio;
 DirectionsRepository({required Dio dio}) : _dio = dio;

Future<Directions?> getRouteBetweenCoordinates({
required LatLng origin,
required LatLng destination,
   }) async {
    debugPrint('getting direction');  
    final response = await _dio.get(
  _baseUrl,
  queryParameters: {
    'origin': '${origin.latitude},${origin.longitude}',
    'destination': '${destination.latitude},${destination.longitude}',
    'key': 'google-directions-api-key',
  },
);

if (response.statusCode == 200) {
  if (response.data['routes'].length < 1) {
    return null;
  }
  return Directions.fromMap(response.data);
    } else {
      debugPrint('response => $response');
    }
     return null;
   }
 }

The Direction Model:

import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class Directions {
  final LatLngBounds bounds;
  final List<PointLatLng> polylinePoints;
  final String totalDistance;
  final String totalDuration;

  const Directions({
    required this.bounds,
    required this.polylinePoints,
    required this.totalDistance,
    required this.totalDuration,
  });

factory Directions.fromMap(Map<String, dynamic> map) {

final data = Map<String, dynamic>.from(map['routes'][0]);

// Bounds
final northeast = data['bounds']['northeast'];
final southwest = data['bounds']['southwest'];
final bounds = LatLngBounds(
  northeast: LatLng(northeast['lat'], northeast['lng']),
  southwest: LatLng(southwest['lat'], southwest['lng']),
);

// Distance & Duration
String distance = '';
String duration = '';
if ((data['legs'] as List).isNotEmpty) {
  final leg = data['legs'][0];
  distance = leg['distance']['text'];
  duration = leg['duration']['text'];
}

return Directions(
  bounds: bounds,
  polylinePoints:
      PolylinePoints().decodePolyline(data['overview_polyline']. 
['points']),
  totalDistance: distance,
  totalDuration: duration,
    );
  }
}

To get the Polylines:

final Directions? directions = await DirectionsRepository(dio: Dio())
    .getRouteBetweenCoordinates(origin: origin, destination: dest);
if (directions == null) return;

_info = directions;

_polylines = {
  Polyline(
    polylineId: const PolylineId('direction_polyline'),
    color: Theme.of(context).colorScheme.primary,
    width: 5,
    points: _info!.polylinePoints
        .map((e) => LatLng(e.latitude, e.longitude))
        .toList(),
    )
  };
}