Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

Flutter: How to add marker to Google Maps with new Marker API?

    mapController.addMarker(
  MarkerOptions(
    position: LatLng(37.4219999, -122.0862462),
  ),
);

I've seen this code snippet in a blog post, and I'm trying to add markers to Google Maps.

The method 'addMarker' isn't defined for the class 'GoogleMapController'.

I think the library has changed and I want to know what's the new way doing this, I've looked up in the controller.dart and api reference but couldn't figure it out.

I would be happy to see some tutorials and blog posts about it, don't hesitate to share.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, The google maps API has changed and the Marker API is widget based and not based in controller anymore.

By CHANGELOG.md

"Breaking change. Changed the Marker API to be widget based, it was controller based. Also changed the example app to account for the same."

I copy some pieces of code from github app example that I think is important to you

Map<MarkerId, Marker> markers = <MarkerId, Marker>{}; // CLASS MEMBER, MAP OF MARKS

void _add() {
    var markerIdVal = MyWayToGenerateId();
    final MarkerId markerId = MarkerId(markerIdVal);

    // creating a new MARKER
    final Marker marker = Marker(
      markerId: markerId,
      position: LatLng(
        center.latitude + sin(_markerIdCounter * pi / 6.0) / 20.0,
        center.longitude + cos(_markerIdCounter * pi / 6.0) / 20.0,
      ),
      infoWindow: InfoWindow(title: markerIdVal, snippet: '*'),
      onTap: () {
        _onMarkerTapped(markerId);
      },
    );

    setState(() {
      // adding a new marker to map
      markers[markerId] = marker;
    });
}

GoogleMap(
              onMapCreated: _onMapCreated,
              initialCameraPosition: const CameraPosition(
                target: LatLng(-33.852, 151.211),
                zoom: 11.0,
              ),
              // TODO(iskakaushik): Remove this when collection literals makes it to stable.
              // https://github.com/flutter/flutter/issues/28312
              // ignore: prefer_collection_literals
              markers: Set<Marker>.of(markers.values), // YOUR MARKS IN MAP
)

I advise you take a look in example app here. There is updated to new API.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...