我是Android新手。我想在我的应用程序中从一个位置绘制一条线到另一个位置。如何在Android中的两点之间画一条线?请帮帮我。
答案 0 :(得分:1)
您应该向地图添加Overlay
并覆盖它的onDraw()
方法。这样你就可以在地图上绘制任何你想要的东西。
答案 1 :(得分:0)
使用它对我来说很好用
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
ArrayList allGeoPoints = getDirections(8.487495, 76.948623,toLat 10.015861, 76.341867toLon);
GeoPoint moveTo = new GeoPoint(startLattitude, startLongigude);
mapController.setCenter(moveTo);
//mc.animateTo(moveTo);
mapController.setZoom(12);
mapView.getOverlays().add(new MyOverlay(allGeoPoints));
public static ArrayList getDirections(double lat1, double lon1, double lat2, double lon2) {
String url = "http://maps.googleapis.com/maps/api/directions/xml?origin=" +lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric";
String tag[] = { "lat", "lng" };
ArrayList listOfGeopoints = new ArrayList();
HttpResponse response = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
response = httpClient.execute(httpPost, localContext);
InputStream in = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
Log.e("********************** ",new JsonOperations().convertStreamToString(in).toString());
if (doc != null) {
NodeList nl1, nl2;
nl1 = doc.getElementsByTagName(tag[0]);
nl2 = doc.getElementsByTagName(tag[1]);
if (nl1.getLength() > 0) {
listOfGeopoints = new ArrayList();
for (int i = 0; i < nl1.getLength(); i++) {
Node node1 = nl1.item(i);
Node node2 = nl2.item(i);
double lat = Double.parseDouble(node1.getTextContent());
double lng = Double.parseDouble(node2.getTextContent());
listOfGeopoints.add(new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6)));
}
} else {
// No points found
}
}
} catch (Exception e) {
e.printStackTrace();
}
return listOfGeopoints;
}
和myoverlay类
public class MyOverlay extends Overlay {
private ArrayList allGeoPoints;
public MyOverlay(ArrayList allGeoPoints) {
super();
this.allGeoPoints = allGeoPoints;
}
@Override
public boolean draw(Canvas canvas, MapView mv, boolean shadow, long when) {
super.draw(canvas, mv, shadow);
drawPath(mv, canvas);
return true;
}
public void drawPath(MapView mv, Canvas canvas) {
int xPrev = -1, yPrev = -1, xNow = -1, yNow = -1;
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(4);
//paint.setAlpha(100);
if (allGeoPoints != null)
for (int i = 0; i < allGeoPoints.size() - 4; i++) {
GeoPoint gp = (GeoPoint) allGeoPoints.get(i);
Point point = new Point();
mv.getProjection().toPixels(gp, point);
xNow = point.x;
yNow = point.y;
if (xPrev != -1) {
canvas.drawLine(xPrev, yPrev, xNow, yNow, paint);
}
xPrev = xNow;
yPrev = yNow;
}
}
}