【问题标题】:Setting different Icons for markers in flutter google maps在颤动的谷歌地图中为标记设置不同的图标
【发布时间】:2022-07-03 01:45:17
【问题描述】:

我想从本地 json 文件在地图上设置多个标记,每个标记都有不同的图标。我已经尝试了每一个我能找到的“解决方案”,但它们都不起作用。

我有一个我首先初始化的标记列表:List<Marker> allMarkers = [];

然后我为 json 文件中的每个条目创建标记:

List<dynamic> parsedJson = jsonDecode(snapshot.data);
              allMarkers = parsedJson.map((element) {
                return Marker(
                  markerId: MarkerId(element['id']),
                  position: LatLng(element['lat'], element['lng']),
                  icon: element['icon'],
                  infoWindow: InfoWindow(
                    title: element['name'],
                    snippet: element['description']
                  ),
                );
              }).toList();

最后,我使用 markers: Set.from(allMarkers) 将标记添加到 GoogleMap

运行此代码时出现错误type 'string' is not a subtype of type 'BitmapDescriptor'.

我的 json 文件的布局:

[{
  "name": "abc",
  "id": "0",
  "lat": 40.7128,
  "lng": -74.0060,
  "icon": "assets/images/icon1.png",
  "description": "some sample description"
},{
  "name": "abcd",
  "id": "1",
  "lat": 41.7128,
  "lng": -75.0060,
  "type": "assets/images/icon2.png",
  "description": "some sample description"
}]

两个图标都添加到 pubspec.yaml 中,这不是错误。

pastebin 上的完整 main.dart 文件:https://pastebin.com/QNFWcszA

【问题讨论】:

    标签: flutter


    【解决方案1】:

    您需要为图标提供 BitmapDescriptor。你可以这样做:

    icon: BitmapDescriptor.fromBytes(
          await getBytesFromAsset('asset/icons/ic_car_top_view.png', 70)),
    

    Future<Uint8List> getBytesFromAsset(String path, int width) async {
    ByteData data = await rootBundle.load(path);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(),
        targetWidth: width);
    ui.FrameInfo fi = await codec.getNextFrame();
    return (await fi.image.toByteData(format: ui.ImageByteFormat.png))!
        .buffer
        .asUint8List();
    

    }

    更多详细信息,请参考以下链接

    github

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 2020-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-30
      相关资源
      最近更新 更多