如何显示在谷歌地图API的Android V2不同的图标多个标记?(How to display m

2019-07-19 00:03发布

我解析其中包含的数据为我将使用谷歌地图API的Android V2在地图上显示Android应用程序的XML文件。 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>

现在,我想显示与基于图标的在标记元素的属性值不同的图标在地图上的每个标记物。 我目前通过循环添加标记的代码是:

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图标属性每个标记显示不同的图标?

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

Answer 1:

要获取资源:

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

icon上面使用分配可变的XML icon属性

使用此得到icon动态:

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


Answer 2:

尝试如下:

// 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])));
}


文章来源: How to display multiple markers with different icons in Google Maps Android API v2?