Android中Google地图折线层(Polyline)

我的工程在Android Google Map上需要划折线,发现API中竟然没有Polyline,分析Overlay类之后,自己做了一个折线类,使用起来跟Flex中的Polyline差 不多,其余不多说,直接贴上代码。

package westyi.map.overlay;

import java.util.List;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;

/**
 * Goolge地图之Polyline实现
 * 
 * @author westyi
 */
public class Polyline extends Overlay {
	List<GeoPoint> points;
	Paint paint;

	/**
	 * 构造函数,使用GeoPoint List构造Polyline
	 * 
	 * @param points
	 *            GeoPoint点List
	 */
	public Polyline(List<GeoPoint> points) {
		this.points = points;
		paint = new Paint();
		paint.setColor(Color.BLUE);
		paint.setAlpha(150);
		paint.setAntiAlias(true);
		paint.setStyle(Paint.Style.FILL_AND_STROKE);
		paint.setStrokeWidth(4);
	}

	/**
	 * 使用GeoPoint点List和Paint对象来构造Polyline
	 * 
	 * @param points
	 *            GeoPoint点List,所有的拐点
	 * @param paint
	 *            Paint对象,用来控制划线样式
	 */
	public Polyline(List<GeoPoint> points, Paint paint) {
		this.points = points;
		this.paint = paint;
	}


	/**
	 * 真正将线绘制出来 只需将线绘制到canvas上即可,主要是要转换经纬度到屏幕坐标
	 */
	@Override
	public void draw(Canvas canvas, MapView mapView, boolean shadow) {
		if (!shadow) {// 不是绘制shadow层
			Projection projection = mapView.getProjection();
			if (points != null) {
				if (points.size() >= 2) {
					Point start = projection.toPixels(points.get(0), null);// 需要转换坐标
					for (int i = 1; i < points.size(); i++) {
						Point end = projection.toPixels(points.get(i), null);
						canvas.drawLine(start.x, start.y, end.x, end.y, paint);// 绘制到canvas上即可
						start = end;
					}
				}
			}
		}
	}
}

 简单的用例如下:

List<GeoPoint> points = new ArrayList<GeoPoint>();
points.add(new GeoPoint(39907794,116356694));
points.add(new GeoPoint(39950181,116415059));
points.add(new GeoPoint(39909637,116435315));
points.add(new GeoPoint(39902526,116398236));
Polyline polyline = new Polyline(points);
map.getOverlays().add(polyline); //map是MapView类型
map.invalidate();
 

OK, 大功告成!看看效果如下:

带折线的Google地图

你可能感兴趣的:(android,Flex,Google)