Flutter:如何使用新的Marker API将标记添加到Google Maps?

问题描述:

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

我在博客文章,我正在尝试将标记添加到Google地图.

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

未为类"GoogleMapController"定义方法"addMarker".

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

我认为库已更改,我想知道执行此操作的新方法,我在 api参考,但无法弄清楚.

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.

是的,google maps API已更改,并且Marker API是基于小部件的,不再基于控制器.

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

通过 CHANGELOG.md

发生了很大的变化.将Marker API更改为基于小部件,它是基于控制器的.还更改了示例应用程序以解决该问题."

我从 github应用示例

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.