0

I am implementing google map in my flutter project and I am getting this error Failed assertion: line 22 pos 16: 'target != null': is not true as a red error screen for 2 seconds on my mobile device, and then the map got implemented.

How to solve that ?

here is the code:

body: GoogleMap(
        polylines: _polyLines,
        markers: _markers,
        mapType: MapType.normal,
        initialCameraPosition: CameraPosition(
          target: latLng,
          zoom: 14,
        ),
        onCameraMove: onCameraMove,
        onMapCreated: (GoogleMapController controller) {
          _controller.complete(controller);
        },
        myLocationEnabled: true,
      ),

2 Answers2

1

Answer First

SO what I here do, first I get current location using the geolocator: ^6.1.13 plugin and simply save it into one variable and until get current location show empty container and then pass the current location to the target value in Google map

class SelectionScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _selectionScreen();
  }
}

class _selectionScreen extends State<SelectionScreen> {
  @override
  initState() {
    loading = false;
    getCurrentLocation();
    super.initState();
  }
 bool loading;
  var start_currentPostion;

  getCurrentLocation() async {
    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);

    setState(() {
      double latitude = position.latitude;
      double longitude = position.longitude;
      start_currentPostion = LatLng(latitude, longitude);
      loading = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        body: loading ? GoogleMap(
          mapType: MapType.normal,
          initialCameraPosition: CameraPosition(
            target: start_currentPostion,
            zoom: 14,
          ),
          onMapCreated: (GoogleMapController controller) {},
          myLocationEnabled: true,
        ) : Container());
  }
}

Answer Second

So in your GoogleMapPage You just need to add one boolean value and update this on the basis of location

bool getLocationLoading;

Add this value in your initState() and set it as false after that again call this boolean variable to your getLocation() method and set it as true

  @override
  void initState() {
    super.initState();
    getLocation();
    getLocationLoading = false;   // set false
  }

  getLocation() async {
    var location = new Location();
    location.onLocationChanged.listen((currentLocation) {
      print(currentLocation.latitude);
      print(currentLocation.longitude);
      setState(() {
        latLng =  LatLng(currentLocation.latitude, currentLocation.longitude);
      });

      print("getLocation:$latLng");
      _onAddMarkerButtonPressed();
      getLocationLoading = true;   // set true

    });

  }

and then simply add your GoogleMap to your body part

body: getLocationLoading ? GoogleMap(
  polylines: _polyLines,
  markers: _markers,
  mapType: MapType.normal,
  initialCameraPosition: CameraPosition(
  target: latLng,
  zoom: 14,
  ),
  onCameraMove: onCameraMove,
  onMapCreated: (GoogleMapController controller) {
  _controller.complete(controller);
  },
  myLocationEnabled: true,
  ), : Container());
Shubham Narkhede
  • 2,002
  • 1
  • 5
  • 13
-1

Here is my code: google_map.dart

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
import 'package:thehelpdesk/components/home/map_request.dart';
import 'package:thehelpdesk/widgets/appbar.dart';

import 'dart:async';

class GoogleMapPage extends StatefulWidget {
  @override
  _GoogleMapPageState createState() => _GoogleMapPageState();
}

class _GoogleMapPageState extends State<GoogleMapPage> {

  Completer<GoogleMapController> _controller = Completer();
  final Set<Marker> _markers = {};
  static LatLng latLng;

  LocationData currentLocation;
  bool loading = true;

  GoogleMapsServices _googleMapsServices = GoogleMapsServices();

  final Set<Polyline> _polyLines = {};
  Set<Polyline> get polyLines => _polyLines;

  void _onAddMarkerButtonPressed() {
    setState(() {
      _markers.add(Marker(
        markerId: MarkerId("111"),
        position: latLng,
        icon: BitmapDescriptor.defaultMarker,
      ));
    });
  }

  getLocation() async {
    var location = new Location();
    location.onLocationChanged.listen((currentLocation) {
      print(currentLocation.latitude);
      print(currentLocation.longitude);
      setState(() {
        latLng =  LatLng(currentLocation.latitude, currentLocation.longitude);
      });

      print("getLocation:$latLng");
      _onAddMarkerButtonPressed();
      loading = false;

    });

  }

  void onCameraMove(CameraPosition position) {
    latLng = position.target;
  }

  @override
  void initState() {
    // setState(() {
    //   getLocation();
    // });
    super.initState();
    if(this.mounted) {
      setState(() {
        getLocation();
      });
    }
  }

  void sendRequest() async {
    LatLng destination = LatLng(20.2961, 85.8245);
    String route = await _googleMapsServices.getRouteCoordinates(
        latLng, destination);
    createRoute(route);
    _addMarker(destination,"Bhubaneswar");
  }

  void createRoute(String encondedPoly) {
    _polyLines.add(Polyline(
        polylineId: PolylineId(latLng.toString()),
        width: 4,
        points: _convertToLatLng(_decodePoly(encondedPoly)),
        color: Colors.red));
  }

  void _addMarker(LatLng location, String address) {
    _markers.add(Marker(
        markerId: MarkerId("112"),
        position: location,
        infoWindow: InfoWindow(title: address, snippet: "go here"),
        icon: BitmapDescriptor.defaultMarker));
  }

  List<LatLng> _convertToLatLng(List points) {
    List<LatLng> result = <LatLng>[];
    for (int i = 0; i < points.length; i++) {
      if (i % 2 != 0) {
        result.add(LatLng(points[i - 1], points[i]));
      }
    }
    return result;
  }

  List _decodePoly(String poly) {
    var list = poly.codeUnits;
    var lList = new List();
    int index = 0;
    int len = poly.length;
    int c = 0;
    do {
      var shift = 0;
      int result = 0;

      do {
        c = list[index] - 63;
        result |= (c & 0x1F) << (shift * 5);
        index++;
        shift++;
      } while (c >= 32);
      if (result & 1 == 1) {
        result = ~result;
      }
      var result1 = (result >> 1) * 0.00001;
      lList.add(result1);
    } while (index < len);

    for (var i = 2; i < lList.length; i++) lList[i] += lList[i - 2];

    print(lList.toString());

    return lList;
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: aapBarSection('Google Map', Colors.blueAccent[700], context),
      body: GoogleMap(
        polylines: _polyLines,
        markers: _markers,
        mapType: MapType.normal,
        initialCameraPosition: CameraPosition(
          target: latLng,
          zoom: 14,
        ),
        onCameraMove: onCameraMove,
        onMapCreated: (GoogleMapController controller) {
          _controller.complete(controller);
        },
        myLocationEnabled: true,
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () {
          sendRequest();
        },
        label: Text('Destination'),
        icon: Icon(Icons.directions),
      ),
    );
  }
}

map_request.dart

import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

const apiKey = "My API Key";

class GoogleMapsServices{
  Future<String> getRouteCoordinates(LatLng l1, LatLng l2) async{
    String url = "https://maps.googleapis.com/maps/api/directions/json?origin=${l1.latitude},${l1.longitude}&destination=${l2.latitude},${l2.longitude}&key=$apiKey";
    http.Response response = await http.get(url);
    Map values = jsonDecode(response.body);
    print("====================>>>>>>>>$values");

    return values["routes"][0]["overview_polyline"]["points"];
  }
}