下文為各位重點介紹關於Android高德地圖自定義Markers的例子,希望這篇文章能夠讓各位理解到Android高德地圖自定義Markers的方法。
之前的博客里說了地圖的嵌入和定位,今天就說說在地圖上顯示一些我們想要的。在地圖中有自帶的Markers(標記),但是它只顯示一個橢圓的圖標,一般是不符合我們的需求的,這樣就要我們自己來自定義。首先標記有下面一些屬性;
1.position(Required) 在地圖上標記位置的經緯度值。參數不能為空。
2.title 當用戶點擊標記,在信息窗口上顯示的字符串。
3.snippet 附加文本,顯示在標題下方。
4.draggable 如果您允許用戶可以自由移動標記,設置為“ true ”。默認情況下為“ false ”。
5.visible 設置“ false ”,標記不可見。默認情況下為“ true ”。
6.anchor圖標擺放在地圖上的基准點。默認情況下,錨點是從圖片下沿的中間處。
7.perspective設置 true,標記有近大遠小效果。默認情況下為 false。
8.可以通過Marker.setRotateAngle() 方法設置標記的旋轉角度,從正北開始,逆時針計算。如設置旋轉90度,Marker.setRotateAngle(90)
9.通過setFlat() 方法設置標志是否貼地顯示
自定義圖標通常由 BitmapDescriptor 設置。我們可以在類 BitmapDescriptorFactory 使用以下其中一種方法定義。
1.fromAsset(String assetName) 在 assets 目錄中使用圖像創建自定義標記。
2.fromBitmap (Bitmap image) 使用位圖圖像創建自定義標記。
3.fromFile (String path) 指定路徑的文件創建自定義圖標。
4.fromResource (int resourceId) 使用已經存在的資源創建自定義圖標。先看一下要實現的效果:
地圖自帶標記
實現效果
實現思路是:自定義布局,獲取數據填入相應位置,然后將view轉成Bitmap,調用AMap.addMarker(markerOptions) 方法添加到地圖上。
-
自定義布局並填充數據:
for (int i = 0; i < positionEneityList.size(); i++) { if (positionEneityList.get(i).getType().equals("1")) { View view = View.inflate(getActivity(),R.layout.view_day, null); TextView tv_price = (TextView) view.findViewById(R.id.tv_price); TextView tv_price_status = (TextView) view.findViewById(R.id.tv_price_status); tv_price.setText(positionEneityList.get(i).getPrice()); tv_price_status.setText("元/時"); Bitmap bitmap = CommentActivity.convertViewToBitmap(view); drawMarkerOnMap(new LatLng(Double.parseDouble(positionEneityList.get(i).getLatitude()) , Double.parseDouble(positionEneityList.get(i).getLongitude())), bitmap, positionEneityList.get(i).getId()); } }
2.轉成Bitmap:
//view 轉bitmap public static Bitmap convertViewToBitmap(View view) { view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); view.buildDrawingCache(); Bitmap bitmap = view.getDrawingCache(); return bitmap; }
3.添加到地圖上:
/** * 在地圖上畫marker * * @param point marker坐標點位置(example:LatLng point = new LatLng(39.963175, * 116.400244); ) * @param markerIcon 圖標 * @return Marker對象 */ private Marker drawMarkerOnMap(LatLng point, Bitmap markerIcon, String id) { if (aMap != null && point != null) { Marker marker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 1) .position(point) .title(id) .icon(BitmapDescriptorFactory.fromBitmap(markerIcon))); return marker; } return null; }
這樣就實現了上述效果。