M.Jehan
M.Jehan

Reputation: 11

The method 'addMarker' isn't defined for the type 'GoogleMapController'

I'm adding removeMarker and addMarker but it showing- "The method 'addMarker' isn't defined for the type 'GoogleMapController'.Try correcting the name to the name of an existing method, or defining a method named 'addMarker'."

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geoflutterfire/geoflutterfire.dart';
import 'package:rxdart/rxdart.dart';
import 'dart:async';


void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
        home: Scaffold(
          body: FireMap(),
        )
    );
  }
}

class FireMap extends StatefulWidget {
  const FireMap({Key? key}) : super(key: key);

  @override
  State createState() => FireMapState();
}


class FireMapState extends State<FireMap> {
  late GoogleMapController mapController;
  Location location = Location();
  //Firestore firestore = Firestore.instance;
  FirebaseFirestore firestore = FirebaseFirestore.instance;
  Geoflutterfire geo = Geoflutterfire();

  // Stateful Data
  BehaviorSubject<double> radius = BehaviorSubject();
  late Stream<dynamic>query;

  // Subscription
  late StreamSubscription subscription;

  build(context) {
    return Stack(children: [

      GoogleMap(
        initialCameraPosition: const CameraPosition(
            target: LatLng(24.142, -110.321),
            zoom: 15
        ),
        onMapCreated: _onMapCreated,
        myLocationEnabled: true,
        mapType: MapType.hybrid,
        compassEnabled: true,
        onCameraMove: _animateToUser(),
      ),
      Positioned(
          bottom: 50,
          right: 10,
          child:
          FlatButton(
              child: const Icon(Icons.pin_drop, color: Colors.white),
              color: Colors.green,
              onPressed: _addGeoPoint
          )
      ),
      Positioned(
          bottom: 50,
          left: 10,
          child: Slider(
            min: 100.0,
            max: 500.0,
            divisions: 4,
            value: radius.value,
            label: 'Radius ${radius.value}km',
            activeColor: Colors.green,
            inactiveColor: Colors.green.withOpacity(0.2),
            onChanged: _updateQuery,
          )
      )
    ]);
  }
  _onMapCreated(GoogleMapController controller) {
    _startQuery();
    setState(() {
      mapController = controller;
    });
  }

  addMarker() {
    final Marker marker = Marker(
        markerId: MarkerId,
        position: mapController.cameraPosition.target,
        icon: BitmapDescriptor.defaultMarker,
        infoWindow: InfoWindow.noText,
        //infoWindowText: const InfoWindowText('Magic Marker', '🍄🍄🍄')
    );
    mapController.addMarker();
  }

  _animateToUser() async {
    var pos = await location.getLocation();
    mapController.animateCamera(CameraUpdate.newCameraPosition(
        CameraPosition(
          target: LatLng(pos['latitude'], pos['longitude']),
          zoom: 17.0,
        )
    )
    );
  }
  Future<DocumentReference> _addGeoPoint() async {
    var pos = await location.getLocation();
    GeoFirePoint point = geo.point(latitude: pos['latitude'], longitude: pos['longitude']);
    return firestore.collection('locations').add({
      'position': point.data,
      'name': 'Yay I can be queried!'
    });
  }

  void _updateMarkers(List<DocumentSnapshot> documentList) {
    print(documentList);
    mapController.clearMarkers;
    for (var document in documentList) {
      GeoPoint pos = document.data['position']['geopoint'];
      double distance = document.data['distance'];
      var marker = MarkerOptions(
          position: LatLng(pos.latitude, pos.longitude),
          icon: BitmapDescriptor.defaultMarker,
          infoWindowText: InfoWindowText('Magic Marker', '$distance kilometers from query center')
      );


      mapController.addMarker(marker);
    }
  }

  _startQuery() async {
    // Get users location
    var pos = await location.getLocation();
    double lat = pos['latitude'];
    double lng = pos['longitude'];


   
    var ref = firestore.collection('locations');
    GeoFirePoint center = geo.point(latitude: lat, longitude: lng);

 
    subscription = radius.switchMap((rad) {
      return geo.collection(collectionRef: ref).within(
          center: center,
          radius: rad,
          field: 'position',
          strictMode: true
      );
    }).listen(_updateMarkers);
  }

  _updateQuery(value) {
    final zoomMap = {
      100.0: 12.0,
      200.0: 10.0,
      300.0: 7.0,
      400.0: 6.0,
      500.0: 5.0
    };
    final zoom = zoomMap[value];
    mapController.moveCamera(CameraUpdate.zoomTo(zoom));

    setState(() {
      radius.add(value);
    });
  }

  @override
  dispose() {
    subscription.cancel();
    super.dispose();
  }

}

The getter 'clearMarkers' isn't defined for the type 'GoogleMapController'. Try importing the library that defines 'clearMarkers', correcting the name to the name of an existing getter, or defining a getter or field named 'clearMarkers.The method 'MarkerOptions' isn't defined for the type 'FireMapState'.Try correcting the name to the name of an existing method, or defining a method named 'MarkerOptions'.The method 'InfoWindowText' isn't defined for the type 'FireMapState'. Try correcting the name to the name of an existing method, or defining a method named 'InfoWindowText'.

This error are found in this code.

Upvotes: 1

Views: 1264

Answers (1)

jabamataro
jabamataro

Reputation: 1232

There is no addMarker method for the GoogleMapController. To add markers on your map you need to pass a list of Marker() objects to your GoogleMaps() widget. Here is how to do it:

You need to initialize a list where you will store all of Marker() objects:

 List<Marker> _markers = <Marker>[];

You can add Marker() objects on that list by using _markers.add(). For example, this can be done inside the initState() method:

@override
void initState() {
  // TODO: implement initState
  super.initState();
  _markers.add(
    Marker(
      markerId: MarkerId('markerId'),
      position: LatLng(37.421946, -122.084090),
    ),
   );
}

Lastly, you can add the list of Marker() objects to your GoogleMap() widget:

GoogleMap(
  mapType: MapType.normal,
  markers: Set.from(_markers), /* <---- here is how to add the list of markers */
  initialCameraPosition: _initialCameraPosition,
  onMapCreated: _onMapCreated,
),

You can delete markers by removing it from _markers[] list.

Upvotes: 0

Related Questions