Dammyololade / flutter_polyline_points

A flutter plugin that's decodes encoded google poly line string into list of geo-coordinates suitable for showing route/polyline on maps
MIT License
107 stars 132 forks source link

Polyline not drawing on map #37

Closed rizalsafril closed 4 years ago

rizalsafril commented 4 years ago

Hi..I have an issue here. everything is working fine except polyline is not drawing the street line between destination and origin. any update on this?

Thanks for your time cheers

Dammyololade commented 4 years ago

Can u check your logs for possible errors thrown? Also did you enable billing on your google cloud console for the api-key you are using?

yousefff7 commented 4 years ago

I got the same issue :( , I already enabled billing in my account and there is no errors in logs. Thanks for your effort,

ghike commented 4 years ago

I was having the same problem. Then, I was reviewing my code and I forgot to call the polylines property inside my GoogleMap().

I've just added polylines: _polylines and voilà! It worked like a charm!

rizalsafril commented 4 years ago

Can u check your logs for possible errors thrown? Also did you enable billing on your google cloud console for the api-key you are using?

no errors thrown..and I have enabled my billing. everythings work fine, markers are displayed on map, only polyline is missing

rizalsafril commented 4 years ago

I was having the same problem. Then, I was reviewing my code and I forgot to call the polylines property inside my GoogleMap().

I've just added polylines: _polylines and voilà! It worked like a charm!

can u show me your code? because I did the same but polyline is still missing

rizalsafril commented 4 years ago

`import 'dart:async';

import 'package:beliaja/database/location/device_location.dart';

import 'package:beliaja/shared/secret_api.dart'; import 'package:beliaja/shared/warna.dart'; import 'package:flutter/material.dart'; import 'package:flutter_polyline_points/flutter_polyline_points.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:location/location.dart';

class MapLocation extends StatefulWidget { MapLocation({Key key}) : super(key: key);

@override _MapLocationState createState() => _MapLocationState(); }

class _MapLocationState extends State { Completer _controller = Completer(); double destlat = 5.552780; double destlong = 95.298019;

///LocationData to save ///latitude and longitude Location location = Location(); Future _currentLocation;

////Custom icon BitmapDescriptor originIcon; BitmapDescriptor destIcon;

///Polyline inside Googlemap Map<MarkerId, Marker> markers = {}; Map<PolylineId, Polyline> polylines = {}; List polylineCoordinates = []; PolylinePoints polylinePoints = PolylinePoints(); String googleAPiKey = Secrets.API_KEY;

@override void initState() { super.initState(); _createIcon(); _currentLocation = LocationDevice().getLocation(); }

@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Warna.green, title: Text( "Lokasi Peta", style: TextStyle(color: Colors.white), ), ), body: Stack( children: [ FutureBuilder( future: LocationDevice().checkDevice(), builder: (BuildContext context, snapshot) { switch (snapshot.connectionState) { case (ConnectionState.waiting): return Center( child: CircularProgressIndicator(), ); default: return Container(); } }, ), FutureBuilder( future: _currentLocation, builder: (BuildContext context, AsyncSnapshot data) { switch (data.connectionState) { case (ConnectionState.waiting): return Center( child: CircularProgressIndicator(), ); default: return GoogleMap( mapType: MapType.normal, myLocationEnabled: true, compassEnabled: true, initialCameraPosition: CameraPosition( target: LatLng(data.data.latitude, data.data.longitude), // tilt: 59.440717697143555, zoom: 15.0, ), onMapCreated: (GoogleMapController controller) { _controller.complete(controller);

                  ///Calling polyline
                  _getPolyline(
                    data.data.latitude,
                    data.data.longitude,
                    destlat,
                    destlong,
                  );

                  /// origin marker
                  _addMarker(
                      LatLng(
                        data.data.latitude,
                        data.data.longitude,
                      ),
                      "Lokasi anda",
                      originIcon);

                  /// destination marker
                  _addMarker(
                      LatLng(
                        destlat,
                        destlong,
                      ),
                      "Tujuan",
                      destIcon);
                },
                markers: Set<Marker>.of(markers.values),
                polylines: Set<Polyline>.of(polylines.values),
                circles: Set.from([
                  Circle(
                    circleId: CircleId("circle"),
                    center: LatLng(data.data.latitude, data.data.longitude),
                    fillColor: Colors.blue.withOpacity(0.9),
                    strokeColor: Colors.blue.withOpacity(0.9),
                    radius: 1000,
                  )
                ]),
              );
          }
        },
      ),
    ],
  ),
);

}

////We make Icon function. This icon ///will be inserted inside google map as marker Future _createIcon() async { BitmapDescriptor.fromAssetImage(ImageConfiguration(size: Size(12, 12)), "assets/images/pin-origin-128.png") .then((value) => originIcon = value);

BitmapDescriptor.fromAssetImage(
        ImageConfiguration(size: Size(12, 12)), "assets/images/pin-128.png")
    .then((value) => destIcon = value);

}

///Function to add marker _addMarker(LatLng position, String id, BitmapDescriptor descriptor) { MarkerId markerId = MarkerId(id); Marker marker = Marker(markerId: markerId, icon: descriptor, position: position); markers[markerId] = marker; }

///Cal polyline _addPolyLine() { PolylineId id = PolylineId("poly"); Polyline polyline = Polyline( polylineId: id, color: Colors.red, points: polylineCoordinates); polylines[id] = polyline; setState(() {}); }

////Add polyline to map _getPolyline(double _originLatitude, double _originLongitude, double _destLatitude, double _destLongitude) async { PolylineResult result = await polylinePoints.getRouteBetweenCoordinates( googleAPiKey, PointLatLng(_originLatitude, _originLongitude), PointLatLng(_destLatitude, _destLongitude), travelMode: TravelMode.driving, wayPoints: [PolylineWayPoint(location: "Your Location, Indonesia")]); if (result.points.isNotEmpty) { result.points.forEach((PointLatLng point) { polylineCoordinates.add(LatLng(point.latitude, point.longitude)); }); } _addPolyLine(); } }

=============Class location=========== Location location = new Location(); bool _serviceEnabled; PermissionStatus _permissionGranted;

class LocationDevice { Future checkDevice() async { try { _serviceEnabled = await location.serviceEnabled(); _permissionGranted = await location.hasPermission();

  if (!_serviceEnabled) {
    _serviceEnabled = await location.requestService();
    if (!_serviceEnabled) {
      return false;
    }
  }
  if (_permissionGranted == PermissionStatus.denied) {
    _permissionGranted = await location.requestPermission();
    if (_permissionGranted != PermissionStatus.granted) {
      return false;
    }
  }

  return true;
} on PlatformException catch (e) {
  print("Pesan Kesalahan ==> $e");
  return false;
}

}

Future getLat() async { var lokasi; lokasi = await location.getLocation();

return lokasi.latitude;

}

Future getLocation() async { return await location.getLocation(); } }`

Dammyololade commented 4 years ago

Can you share a sample code or possibly a demo project to replicate this issue you are having?

rizalsafril commented 4 years ago

Can you share a sample code or possibly a demo project to replicate this issue you are having?

Thanks...already posted above..

Dammyololade commented 4 years ago

Or can you print the result of await polylinePoints.getRouteBetweenCoordinates()? and also, remove waypoint and try making the request, lets see if its going to come back with a result

ericel commented 4 years ago

This happens to me with coordinates in South Korea. Works fine with US coordinates. But with Korean coordinates, it returns result.points as an empty list [].

What can be the problem?

GoogleMap(
          //myLocationEnabled: true,
          compassEnabled: false,
          tiltGesturesEnabled: false,
          scrollGesturesEnabled: true,
          zoomGesturesEnabled: true,
          markers: _markers,
          polylines: _polylines,
          mapType: MapType.normal,
          initialCameraPosition: initialLocation,
          onMapCreated: onMapCreated);

Not error is displayed.

rizalsafril commented 4 years ago

Or can you print the result of await polylinePoints.getRouteBetweenCoordinates()? and also, remove waypoint and try making the request, lets see if its going to come back with a result

The result of await polylinePoints is Instance of 'PolylineResult'

Dammyololade commented 4 years ago

@ericel av u tried calling the google api directly, probably from postman, i think you might have this issue if google doesn't have data for your request

Dammyololade commented 4 years ago

Or can you print the result of await polylinePoints.getRouteBetweenCoordinates()? and also, remove waypoint and try making the request, lets see if its going to come back with a result

The result of await polylinePoints is Instance of 'PolylineResult'

can you check the points property of the result, what's the length? is there any coordinate return?

ericel commented 4 years ago

@ericel av u tried calling the google api directly, probably from postman, i think you might have this issue if google doesn't have data for your request

The map displays the markers. I will think it means google has the data?

Dammyololade commented 4 years ago

@ericel av u tried calling the google api directly, probably from postman, i think you might have this issue if google doesn't have data for your request

The map displays the markers. I will think it means google has the data?

The amp can show the marker because you are plotting on a coordinate, but that does not mean, google has information about the direction between that coordinate and another location

ericel commented 4 years ago

You are right!

@ericel av u tried calling the google api directly, probably from postman, i think you might have this issue if google doesn't have data for your request

The map displays the markers. I will think it means google has the data?

The amp can show the marker because you are plotting on a coordinate, but that does not mean, google has information about the direction between that coordinate and another location

You are right! That should be the only explanation for the behavior.

rizalsafril commented 4 years ago

Or can you print the result of await polylinePoints.getRouteBetweenCoordinates()? and also, remove waypoint and try making the request, lets see if its going to come back with a result

The result of await polylinePoints is Instance of 'PolylineResult'

can you check the points property of the result, what's the length? is there any coordinate return?

it returns null. I think I will go with your conclusion. it seems google has no information about particular location. Thanks @ericel for your additional info

rizalsafril commented 4 years ago

@Dammyololade thanks for your support. I updated my info, the polyline starts drawing now after I activated Direction API in google cloud platform..I think that caused a problem.

Dammyololade commented 4 years ago

wow, good to hear that.