下面方法只能用來畫點到點的直線,如果想畫兩地點之間的多點導航路線(需連網) 請參考

(兩點距離:米)http://fecbob.pixnet.net/blog/post/36037289-android%E8%A8%88%E7%AE%97%E5%9C%B0%E5%9C%96%E4%B8%8A%E5%85%A9%E9%BB%9E%E8%B7%9D%E9%9B%A2

範例: http://www.linuxidc.com/Linux/2011-05/36375p2.htm

觀念: http://www.cnblogs.com/janken/archive/2012/05/08/2489575.html

Google Directions API : https://developers.google.com/maps/documentation/directions/?hl=zh-TW


首先先將下面的程式碼寫成外部或內部的class 此class 的建構子只要給好路徑的座標(依順序)就可以繪製直線路線(不需網路)

class MapViewDrawPath extends Overlay{
    	GeoPoint[] geoPoints = null;
    	Point[] points = null;
    	Path[] paths = null;
    	float[] drawPoint = null;
    	
    	/**
    	 * 
    	 * @param geoPoints 路徑座標(請依序排列)
    	 */
    	public MapViewDrawPath(GeoPoint...geoPoints){
    		this.geoPoints = geoPoints;
    		
    		//初始化Point
    		points = new Point[geoPoints.length];
    		for(int i=0 ; i < points.length ; i++)points[i] = new Point();
    		
    		//初始化Path
    		paths = new Path[geoPoints.length-1];//路徑數比座標數少1
    		for(int i=0;i< paths.length;i++)paths[i] = new Path();
    		
    		drawPoint = new float[(geoPoints.length-1)*4];
    	}
    	
    	@Override
    	public void draw(Canvas canvas,MapView mapView,boolean shadow){
    		super.draw(canvas, mapView, shadow);
    		
    		Paint paint = new Paint();
    		paint.setColor(Color.GRAY);//畫筆的顏色
    		paint.setAlpha(255);//不透明度
    		paint.setDither(true);
    		paint.setStyle(Paint.Style.STROKE);//樣式
    		paint.setStrokeJoin(Paint.Join.ROUND);
    		paint.setStrokeCap(Paint.Cap.ROUND);
    		paint.setStrokeWidth(2);//寬度
    		Projection projection = mapView.getProjection();
    		
    		for(int i=0;i < geoPoints.length;i++){
    			projection.toPixels(geoPoints[i],points[i]);
    		}
    		
    		
    		int count = 0;
    		
    		for(int i=0;i< drawPoint.length;i+=2){
    			if(i==0){
    				drawPoint[i] = points[count].x;
        			drawPoint[i+1] = points[count].y;
        			count++;
    			}else if(i>= drawPoint.length-2){
    				drawPoint[i] = points[points.length-1].x;
        			drawPoint[i+1] = points[points.length-1].y;
    			}else{
    				drawPoint[i] = points[count].x;
        			drawPoint[i+1] = points[count].y;
        			drawPoint[i+2] = points[count].x;
        			drawPoint[i+3] = points[count].y;
        			i+=2;
        			count++;
    			}
    			
    		}
    		
    		canvas.drawLines(drawPoint, paint);
    	}
    }

然後在主要的MapViewActivity裡

//測試資料
GeoPoint g1 = new GeoPoint((int)(25.107984*1000000),(int)(121.562244*1000000));//台北
GeoPoint g2 = new GeoPoint((int)(24.28202*1000000),(int)(120.950821*1000000));//台中
GeoPoint g3 = new GeoPoint((int)(22.763835*1000000),(int)(121.145502*1000000));//台東

//依下面範例撰寫
MapViewDrawPath dp = new MapViewDrawPath(g1,g2,g3);
mapView.getOverlays().add(dp);

, , , ,
創作者介紹

Mazs's Notes

cookiesp 發表在 痞客邦 PIXNET 留言(0) 人氣()