android google 根据字符串参数映射标记

android google maps marker based on string parameter

关于 android 上的 google 地图,我需要一些帮助。我要解决的问题是如何从可绘制文件夹 select 标记图标,并根据通过 ajax 调用收到的参数将其绘制在 google 地图上。这是我试过的

    String img_name = jsonObj.getString("icon_name")+"_"+jsonObj.getString("icon_state") == "0" ? "on" : "off";
    // img_name will get a value thing like 'cat_on', I have the icon in drawable folder

    // how do I use this img_name in the .icon line below


    mMap.addMarker(new MarkerOptions()
        .title(jsonObj.getString("header"))
        .snippet(jsonObj.getString("title").concat(jsonObj.getString("description")))
        .position(new LatLng(
            Double.parseDouble(jsonObj.getString("lat")),
            Double.parseDouble(jsonObj.getString("lng"))
        ))
        .icon(BitmapDescriptorFactory.fromResource(R.id.resourceId))
    );

我不知道我是否完全理解你的问题,但你可以使用

getIdentifier

来自 android 资源以通过名称获取图标的 ID。

像这样:

getResources().getIdentifier("icon_name", "drawable", getPackageName());

例如,如果您从 activity 调用它。

getResources() documentation

更新:

你试过吗?

String img_name = jsonObj.getString("icon_name")+"_"+jsonObj.getString("icon_state") == "0" ? "on" : "off";
    // img_name will get a value thing like 'cat_on', I have the icon in drawable folder

    // how do I use this img_name in the .icon line below
int resourceId = getResources().getIdentifier(img_name, "drawable", getPackageName());

    mMap.addMarker(new MarkerOptions()
        .title(jsonObj.getString("header"))
        .snippet(jsonObj.getString("title").concat(jsonObj.getString("description")))
        .position(new LatLng(
            Double.parseDouble(jsonObj.getString("lat")),
            Double.parseDouble(jsonObj.getString("lng"))
        ))
        .icon(BitmapDescriptorFactory.fromResource(resourceId))
    );