如何使用BitmapDescriptor.fromAssetImage()设置自定义标记图标?

Mic*_*l D 5 google-maps-markers dart flutter

我正在尝试在Flutter应用中为地图标记设置自定义图标。由于BitmapDescriptor.fromAsset()已弃用,因此我正在寻找如何使用BitmapDescriptor.fromAssetImage()

我没有找到关于此的任何文档或Stackoverflow问题。

这是我创建它的当前方式(没有自定义图像):

Marker(
          markerId: MarkerId(pos.toString()),
          position: pos,
          infoWindow: InfoWindow(
            title: store['store_name'],
            snippet: '',
          ),
          icon: BitmapDescriptor.defaultMarker));
Run Code Online (Sandbox Code Playgroud)

小智 16

更好的解决方案是将GoogleMap小部件包装在FutureBuilder 中。在单独的 Future 中生成标记,并将未来的结果分配给 GoogleMap 小部件中的标记

未来建设者:

FutureBuilder(
  future: generateMarkers(positions),
  initialData: Set.of(<Marker>[]),
  builder: (context, snapshot) => GoogleMap(        
    initialCameraPosition: CameraPosition(target: LatLng(0, 0)),
    markers: snapshot.data,
  ),
);
Run Code Online (Sandbox Code Playgroud)

标记生成器:

Future<Set<Marker>> generateMarkers(List<LatLng> positions) async {
List<Marker> markers = <Marker>[];
for (final location in positions) {    
  final icon = await BitmapDescriptor.fromAssetImage(
      ImageConfiguration(size: Size(24, 24)), 'assets/my_icon.png');

  final marker = Marker(
    markerId: MarkerId(location.toString()),
    position: LatLng(location.latitude, location.longitude),
    icon: icon,
  );

  markers.add(marker);
}

return markers.toSet();

}
Run Code Online (Sandbox Code Playgroud)


Aks*_*tel 9

在类中定义一个字段:

BitmapDescriptor myIcon;
Run Code Online (Sandbox Code Playgroud)

在地图准备好之前检索图标。

@override
void initState() {
    BitmapDescriptor.fromAssetImage(
        ImageConfiguration(size: Size(48, 48)), 'assets/my_icon.png')
        .then((onValue) {
      myIcon = onValue;
    });
 }
Run Code Online (Sandbox Code Playgroud)

设置图标:

icon: myIcon;
Run Code Online (Sandbox Code Playgroud)

确保已在pubspec.yaml的Flutter部分中设置了图标

 assets:
    - assets/my_icon.png
Run Code Online (Sandbox Code Playgroud)

  • 由于某种原因,我发现将 `Size(48, 48)` 更改为 `Size(10, 10)` 不会改变图标的​​大小。 (4认同)
  • 我会尝试使用但返回错误..软件说未处理的异常:PlatformException(错误,无法解码图像。提供的图像必须是位图。如何解决?谢谢 (3认同)
  • @JVE999 `ImageConfiguration` 的大小参数被 `BitmapDescriptor` 忽略 (3认同)
  • 大家好,我在应用程序加载之前已在 initState 中加载了图标,我使用记录器确认了它,但在页面加载后我看到错误“com.google.maps.api.android.lib6.common.apiexception.a:无法解码图像” 。提供的图像必须是位图。有人可以帮忙吗?非常感谢 (2认同)
  • 大家好,您在调整图标大小时遇到​​问题吗?就我而言,它不想将大小调整为所需的值。有什么想法吗? (2认同)