0

I am able to show map with custom lat and long but i want to dynamically show marker of shop in google map,but i am kind of stuck at what to next,i tried some example but it i can't figure it out how to do this,can any one help me on this,i have no problem getting the lat and long from api but i am not sure how to set up marker in google map.

Variable initialized

 GoogleMapController mapController;
 final LatLng _center = const LatLng(45.521563, -122.677433);
  Set<Marker> markers = Set();
  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

Map Widget

Widget MapViewData() {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height,
      child: GoogleMap(
        onMapCreated: _onMapCreated,
        initialCameraPosition: CameraPosition(
          target: _center,
          zoom: 11.0,
        ),
      ),
    );
  }

Api functions returs lat and long along with details

 Future<void> Mapdata() async {
    var response = await http.get(
        "${Urls.baseUrl}${Urls.GetMapData}?radius=100&locale=en",
        headers: {
          "Content-Type": "application/json",
          "Authorization": "Bearer ${userToken}",
          "Accept": "application/json"
        });
    Map<String, dynamic> value = json.decode(response.body);
  
    if (response.statusCode == 200) {
      try {
        var data = value['data'];
        var array = data['shops'];
        for (int i = 0; i < array.length; i++) {
          var obj = array[i];
          mapLists.add(NearByMapModel(
            obj['id'],
            obj['name'],
            obj['address'],
            obj['latitude'],
            obj['longitude'],
          ));
       
        }
      } catch (e) {
        e.toString();
      }
    }
  }

2 Answers 2

1

Initialize your markers like this:

  List<Marker> _marker = [];

  void _initMarkers() {
    if (mapLists!= null) {

      _marker.clear();
      for (int i = 0; i < mapLists.length; i++) {
        MarkerId markerId = new MarkerId(i.toString());

        if (mapLists[i].latitude!= null && mapLists[i].longitude!= null) {
          _marker.add(
            new Marker(
              markerId: markerId,
              position: LatLng(mapLists[i].latitude, mapLists[i].longitude)
              onTap: () {
                // Handle on marker tap
              },
              icon: BitmapDescriptor.defaultMarkerWithHue(
                      BitmapDescriptor.hueBlue),
            ),
          );
        } 
      }
    }
  }

and then pass them to GoogleMap:

GoogleMap(
      myLocationEnabled: true,
      zoomControlsEnabled: false,
      indoorViewEnabled: true,
      mapType: MapType.terrain,
      initialCameraPosition: CameraPosition(
        target: _center,
        zoom: 11.0,
      ),
      markers: _marker.toSet(),
      myLocationButtonEnabled: true,
      onMapCreated: (GoogleMapController controller) {
        mapController = controller;
      },
    )
Sign up to request clarification or add additional context in comments.

7 Comments

when i use this _initMarkers() function it shows multiple errors Undefined name '_objs'.,The method '_onMarkerTap' isn't defined for the type '_DashboardNearByScreenState'.,The method '_onMarkerTap' isn't defined for the type '_DashboardNearByScreenState'. @R.Shpd
I updated my answer and used your model. Implement onTap if you need to be aware of selecting a marker by user. @Assassin
still have problem he operator '[]' isn't defined for the type 'Set<Marker>'. and Undefined name '_googlePlex'. @R.Shpd
other error are gone now it throrws another error ` Failed assertion: line 26 pos 16: 'target != null': is not true.`@R.Shpd
As the error said, you can't pass null to the target parameter. @Assassin
|
0

I have figured it out by another example

Initialize variables

  double latti=25.2048493,long=55.2707828;
  Completer<GoogleMapController> _controller = Completer();
  Iterable markers = [];

Map Widget

  Widget MapViewData() {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height,
      child: GoogleMap(
        markers: Set.from(markers),
        initialCameraPosition:
            CameraPosition(
                target: LatLng(latti, long),
                tilt: 30,
                zoom:  14),
        mapType: MapType.normal,
        onMapCreated: (GoogleMapController controller) {
          _controller = controller as Completer<GoogleMapController>;
        },
      ),
    );
  } 

API Call

  Future<void> Mapdata() async {
    var response = await http.get(
        "${Urls.baseUrl}${Urls.GetMapData}?radius=100&locale=en",
        headers: {
          "Content-Type": "application/json",
          "Authorization": "Bearer ${userToken}",
          "Accept": "application/json"
        });
    Map<String, dynamic> value = json.decode(response.body);
 
    if (response.statusCode == 200) {
      try {
        var data = value['data'];
        var array = data['shops'];
        for (int i = 0; i < array.length; i++) {
          var obj = array[i];
        
          mapLists.add(NearByMapModel(
            obj['id'],
            obj['name'],
            obj['address'],
            obj['latitude'],
            obj['longitude'],
          ));

          Iterable _markers = Iterable.generate(mapLists.length, (index) {
            Map result = array[index];
            latti = double.parse(obj["latitude"]);
            long = double.parse(obj["longitude"]);
            LatLng latLngMarker = LatLng(double.parse(result["latitude"]),
                double.parse(result["longitude"]));

            return Marker(
                markerId: MarkerId("marker$index"),
                position: latLngMarker,
                infoWindow: InfoWindow(
                    title: result["name"], snippet: result["address"]));
          });
          setState(() {
            mapLists.length;
            markers = _markers;
            this.latti = latti;
            this.long = long;
          });
        }
      } catch (e) {
        e.toString();
      }
    }
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.