2013-08-05 69 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