2013-08-05 51 views
41

我使用这部分代码在谷歌地图版本添加标记在MapFragment 2.设置图像2

MarkerOptions op = new MarkerOptions(); 
op.position(point) 
    .title(Location_ArrayList.get(j).getCity_name()) 
    .snippet(Location_ArrayList.get(j).getVenue_name()) 
    .draggable(true); 
m = map.addMarker(op); 
markers.add(m); 

我想从我的绘制使用不同的图像。任何帮助将不胜感激。

+6

执行'BitmapDescriptor图标= BitmapDescriptorFactory.fromResource(R.drawable.current_position_tennis_ball)',然后运算。图标(图标); –

+0

Mr.Babar thanx为您的答案它的好处,为我工作...ü发布它作为答案,我会接受它...再次感谢。 – NRahman

+0

@MuhammadBabar我们可以通过图像标题 – Amitsharma

回答

93

这是如何将Drawable设置为Marker

BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.current_position_tennis_ball) 

MarkerOptions markerOptions = new MarkerOptions().position(latLng) 
     .title("Current Location") 
     .snippet("Thinking of finding some thing...") 
     .icon(icon); 

mMarker = googleMap.addMarker(markerOptions); 

VectorDrawablesXML基于Drawables这项工作。

+18

这是正确的,虽然使用“任何”可绘制的单词是不正确的。这只允许你设置BitmapDrawables。例如,你不能用xml设置一个drawable。 –

+3

嗯,你可以 - 你只需要首先将它绘制成一个'Canvas'('drawable.draw(canvas)'),然后将'Canvas'转储到'Bitmap'。 –

+2

好吧,我真的不知道这个权利吧!所以让最后的投票决定谁是正确的:) –

6

如果您Drawable创建编程(所以你自己也没有资源),您可以使用此:

Drawable d = ... // programatically create drawable 
Canvas canvas = new Canvas(); 
Bitmap bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); 
canvas.setBitmap(bitmap); 
d.draw(canvas); 
BitmapDescriptor bd = BitmapDescriptorFactory.fromBitmap(bitmap); 

然后你有BitmapDescriptor,您可以传递到MarkerOptions

+0

这会为我创建空图像 –

+0

请参阅由@vovahost发布的示例,以获取此方法的完整示例。这个答案并不完整。 – Alex

42

@Lukas Novak答案没有显示任何内容,因为您还必须设置Drawable的界限。
这适用于任何drawable。这里是一个完全工作示例:

public void drawMarker() { 
    Drawable circleDrawable = getResources().getDrawable(R.drawable.circle_shape); 
    BitmapDescriptor markerIcon = getMarkerIconFromDrawable(circleDrawable); 

    googleMap.addMarker(new MarkerOptions() 
      .position(new LatLng(41.906991, 12.453360)) 
      .title("My Marker") 
      .icon(markerIcon) 
    ); 
} 

private BitmapDescriptor getMarkerIconFromDrawable(Drawable drawable) { 
    Canvas canvas = new Canvas(); 
    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); 
    canvas.setBitmap(bitmap); 
    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); 
    drawable.draw(canvas); 
    return BitmapDescriptorFactory.fromBitmap(bitmap); 
} 


circle_shape.xml

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> 
    <size android:width="20dp" android:height="20dp"/> 
    <solid android:color="#ff00ff"/> 
</shape> 
+0

这确实是一个完全可行的例子。谢谢 – Odys

+0

我的第一个标记比其他标记更大,我使用与你完全相同的代码。可能是什么原因?它独立于我与其他人一起尝试的图像源。 – Recomer

+0

我不知道。发布一些代码:如果以编程方式创建drawable,则可绘制xml或cose用于创建drawable。 – vovahost