3

我正在解析一个 XML 文件,其中包含我的 Android 应用程序的数据,该数据将使用 Google Maps Android API v2 显示在地图上。XML 文件的示例格式为:

<markers>
  <marker name="San Pedro Cathedral"
          address="Davao City"
          lat="7.0647222"
          long="125.6091667"
          icon="church"/>
  <marker name="SM Lanang Premier"
          address="Davao City"
          lat="7.0983333"
          long="125.6308333"
          icon="shopping"/>
  <marker name="Davao Central High School"
          address="Davao City"
          lat="7.0769444"
          long="125.6136111"
          icon="school"/>
</markers>

现在,我想根据marker元素中icon的属性值,在地图上用不同的图标显示每个标记。我当前通过循环添加标记的代码是:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("http://dds.orgfree.com/DDS/landmarks_genxml.php");

NodeList markers = doc.getElementsByTagName("marker");

for (int i = 0; i < markers.getLength(); i++) {
    Element item = (Element) markers.item(i);
    String name = item.getAttribute("name");
    String address = item.getAttribute("address");
    String stringLat = item.getAttribute("lat");
    String stringLong = item.getAttribute("long");
    String icon = item.getAttribute("icon"); //assigned variable for the XML icon attribute
    Double lat = Double.valueOf(stringLat);
    Double lon = Double.valueOf(stringLong);
    map = ((MapFragment) getFragmentManager().findFragmentById(
            R.id.map)).getMap();

    map.addMarker(new MarkerOptions()
            .position(new LatLng(lat, lon))
            .title(name)
            .snippet(address)
            //I have a coding problem here...
            .icon(BitmapDescriptorFactory
                    .fromResource(R.drawable.icon)));

    // Move the camera instantly to City Hall with a zoom of 15.
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(CITYHALL, 15));

我的可绘制文件夹中有教堂、购物、学校等的所有不同图标。但我的线路有问题:

.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon)

因为R.drawable仅与可绘制文件夹中的文件有关。如何根据 XML 上的图标属性动态地为每个标记显示不同的图标?

任何帮助将不胜感激。:)

4

2 回答 2

4

获取资源:

getResources().getIdentifier(icon,"drawable", getPackageName())

上面使用的是为 XML属性icon分配的变量icon

使用它来icon动态获取:

.icon(BitmapDescriptorFactory
   .fromResource(getResources().getIdentifier(icon,"drawable", getPackageName()))
于 2013-01-30T08:58:22.667 回答
3

尝试如下:

// Creates a marker rainbow demonstrating how to 
// create default marker icons of different.
int numMarkersInRainbow[] = 
{
    R.drawable.arrow,
    R.drawable.badge_nsw,
    R.drawable.badge_qld,
    R.drawable.badge_victoria
};
for (int i = 0; i < markers.getLength(); i++) {
    mMap.addMarker(new MarkerOptions()
        .position(position(new LatLng(lat, lon)))
        .title(name)
        .icon(BitmapDescriptorFactory.fromResource(numMarkersInRainbow[i])));
}
于 2013-01-30T09:19:03.067 回答