Fix a drawing lag during track recording.

For a track with ~2,500 points, the average drawign would take ~30-50ms, now it takes about 20ms (21ms if software clipping is enabled).

Removed all possible congestion points by introducing a blocking queue.

This change includes many fixes, including:
1) Major refactoring and clean up of the overlay, sped up drawing by a factor of 2x
2) Disable software clipping as it was slower by about 5% than w/o clipping and would trigger a bug related to map view spanning
3) Add waypoints synchronization  and fixed a bug related to skipping the first wpt
4) Add a simple unit test
This commit is contained in:
Bartlomiej Niechwiej
2010-10-11 21:55:12 -07:00
parent 01d6dcac59
commit e94338f4c6
4 changed files with 330 additions and 269 deletions
-1
View File
@@ -38,7 +38,6 @@ limitations under the License.
<string name="share_url_only_key">shareUrlOnly</string> <string name="share_url_only_key">shareUrlOnly</string>
<string name="signal_sampling_frequency_key">signalSamplingFrequency</string> <string name="signal_sampling_frequency_key">signalSamplingFrequency</string>
<string name="split_frequency_key">splitFrequency</string> <string name="split_frequency_key">splitFrequency</string>
<string name="debug_draw_bounds_key">debugDrawBounds</string>
<!-- Preference keys which keep transient state (not user preferences) - DO NOT TRANSLATE --> <!-- Preference keys which keep transient state (not user preferences) - DO NOT TRANSLATE -->
<string name="auto_resume_track_current_retry_key">autoResumeTrackCurrentRetry</string> <string name="auto_resume_track_current_retry_key">autoResumeTrackCurrentRetry</string>
@@ -50,14 +50,14 @@ import android.provider.Settings;
import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech;
import android.util.Log; import android.util.Log;
import android.view.ContextMenu; import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.MotionEvent; import android.view.MotionEvent;
import android.view.SubMenu; import android.view.SubMenu;
import android.view.View; import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.Window; import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.ImageButton; import android.widget.ImageButton;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.RelativeLayout; import android.widget.RelativeLayout;
@@ -139,14 +139,16 @@ public class MyTracksMap extends MapActivity
*/ */
private HandlerThread updateTrackThread; private HandlerThread updateTrackThread;
/** Handler for updateTrackThread */ /**
* Handler for updateTrackThread.
*/
private Handler updateTrackHandler; private Handler updateTrackHandler;
private MyTracksProviderUtils providerUtils; private MyTracksProviderUtils providerUtils;
/** /**
* A runnable that updates the track from the provider (looking for points * A runnable that updates the track from the provider (looking for points
* added after "lastSeenLocationId". * added after "lastSeenLocationId").
*/ */
private final Runnable updateTrackRunnable = new Runnable() { private final Runnable updateTrackRunnable = new Runnable() {
@Override @Override
@@ -154,6 +156,7 @@ public class MyTracksMap extends MapActivity
if (!isATrackSelected()) { if (!isATrackSelected()) {
return; return;
} }
readAllNewTrackPoints(); readAllNewTrackPoints();
} }
}; };
@@ -167,6 +170,7 @@ public class MyTracksMap extends MapActivity
if (!isATrackSelected()) { if (!isATrackSelected()) {
return; return;
} }
mapOverlay.clearPoints(); mapOverlay.clearPoints();
firstSeenLocationId = -1; firstSeenLocationId = -1;
lastSeenLocationId = -1; lastSeenLocationId = -1;
@@ -192,14 +196,11 @@ public class MyTracksMap extends MapActivity
cursor = providerUtils.getWaypointsCursor( cursor = providerUtils.getWaypointsCursor(
selectedTrackId, 0, selectedTrackId, 0,
MyTracksConstants.MAX_DISPLAYED_WAYPOINTS_POINTS); MyTracksConstants.MAX_DISPLAYED_WAYPOINTS_POINTS);
if (cursor != null) { if (cursor != null && cursor.moveToFirst()) {
if (cursor.moveToFirst()) {
do { do {
Waypoint wpt = providerUtils.createWaypoint(cursor); mapOverlay.addWaypoint(providerUtils.createWaypoint(cursor));
mapOverlay.addWaypoint(wpt);
} while (cursor.moveToNext()); } while (cursor.moveToNext());
} }
}
} catch (RuntimeException e) { } catch (RuntimeException e) {
Log.w(MyTracksConstants.TAG, "Caught an unexpected exception.", e); Log.w(MyTracksConstants.TAG, "Caught an unexpected exception.", e);
} finally { } finally {
@@ -212,9 +213,9 @@ public class MyTracksMap extends MapActivity
}; };
/** /**
* A runnable intended to be posted to the updateTrackThread after the * A runnable intended to be posted to the {@code #updateTrackThread} after
* selected track changes. It will post to the ui thread to update the screen * the selected track changes. It will post to the UI thread to update
* elements and move the map to show the selected track. * the screen elements and move the map to show the selected track.
*/ */
private final Runnable setSelectedTrackRunnable = new Runnable() { private final Runnable setSelectedTrackRunnable = new Runnable() {
@Override @Override
@@ -372,8 +373,6 @@ public class MyTracksMap extends MapActivity
setSelectedTrack(selectedTrackId); setSelectedTrack(selectedTrackId);
} }
updateOptionsButton(); updateOptionsButton();
mapOverlay.setDrawBounds(preferences.getBoolean(
getString(R.string.debug_draw_bounds_key), false));
preferences.registerOnSharedPreferenceChangeListener(this); preferences.registerOnSharedPreferenceChangeListener(this);
} }
} }
@@ -893,8 +892,7 @@ public class MyTracksMap extends MapActivity
@Override @Override
public void onSharedPreferenceChanged( public void onSharedPreferenceChanged(
final SharedPreferences sharedPreferences, final SharedPreferences sharedPreferences, final String key) {
final String key) {
if (key != null) { if (key != null) {
uiHandler.post(new Runnable() { uiHandler.post(new Runnable() {
@Override @Override
@@ -918,10 +916,6 @@ public class MyTracksMap extends MapActivity
mapOverlay.setShowEndMarker(!isRecordingSelected()); mapOverlay.setShowEndMarker(!isRecordingSelected());
mapView.postInvalidate(); mapView.postInvalidate();
} }
} else if (key.equals(getString(R.string.debug_draw_bounds_key))) {
mapOverlay.setDrawBounds(
sharedPreferences.getBoolean(
getString(R.string.debug_draw_bounds_key), false));
} }
} }
}); });
@@ -950,8 +944,8 @@ public class MyTracksMap extends MapActivity
public void onLocationChanged(Location location) { public void onLocationChanged(Location location) {
if (location.getProvider().equals(MyTracksConstants.GPS_PROVIDER)) { if (location.getProvider().equals(MyTracksConstants.GPS_PROVIDER)) {
// Recalculate the variation if there was a jump in location > 1km: // Recalculate the variation if there was a jump in location > 1km:
if (currentLocation == null if (currentLocation == null ||
|| location.distanceTo(currentLocation) > 1000) { location.distanceTo(currentLocation) > 1000) {
setVariation(location); setVariation(location);
} }
currentLocation = location; currentLocation = location;
@@ -1039,8 +1033,8 @@ public class MyTracksMap extends MapActivity
// Now we already have at least one point, calculate the sampling // Now we already have at least one point, calculate the sampling
// frequency // frequency
long numTotalPoints = lastStoredLocationId - firstSeenLocationId; long numTotalPoints = lastStoredLocationId - firstSeenLocationId;
samplingFrequency = (int) (1 + samplingFrequency = (int) (1 + numTotalPoints
numTotalPoints / MyTracksConstants.TARGET_DISPLAYED_TRACK_POINTS); / MyTracksConstants.TARGET_DISPLAYED_TRACK_POINTS);
} }
providerUtils.fillLocation(cursor, location); providerUtils.fillLocation(cursor, location);
@@ -1052,8 +1046,8 @@ public class MyTracksMap extends MapActivity
if (numPoints % samplingFrequency == 0 || if (numPoints % samplingFrequency == 0 ||
(!isRecordingSelected() && locationId == lastStoredLocationId) || (!isRecordingSelected() && locationId == lastStoredLocationId) ||
!MyTracksUtils.isValidLocation(location)) { !MyTracksUtils.isValidLocation(location)) {
// Only allocate a new location if it is going to be kept around. // No need to allocate a new location (we can safely reuse the existing).
mapOverlay.addLocation(new Location(location)); mapOverlay.addLocation(location);
} }
numPoints++; numPoints++;
@@ -24,16 +24,19 @@ import com.google.android.maps.mytracks.R;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.Paint; import android.graphics.Paint;
import android.graphics.Path; import android.graphics.Path;
import android.graphics.Point; import android.graphics.Point;
import android.graphics.Rect; import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.location.Location; import android.location.Location;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
/** /**
* A map overlay that displays a "MyLocation" arrow, an error circle, the * A map overlay that displays a "MyLocation" arrow, an error circle, the
@@ -43,7 +46,7 @@ import java.util.ArrayList;
*/ */
public class MyTracksOverlay extends Overlay { public class MyTracksOverlay extends Overlay {
private final Drawable arrow[] = new Drawable[18]; private final Drawable[] arrows;
private final int arrowWidth, arrowHeight; private final int arrowWidth, arrowHeight;
private final Drawable statsMarker; private final Drawable statsMarker;
private final Drawable waypointMarker; private final Drawable waypointMarker;
@@ -53,68 +56,89 @@ public class MyTracksOverlay extends Overlay {
private final Paint selectedTrackPaint; private final Paint selectedTrackPaint;
private final Paint errorCirclePaint; private final Paint errorCirclePaint;
private final Context context; private final Context context;
private final ArrayList<Waypoint> waypoints = new ArrayList<Waypoint>(); private final List<Waypoint> waypoints;
private final ArrayList<Location> points = new ArrayList<Location>(1024); private final List<CachedLocation> points;
private final BlockingQueue<CachedLocation> pendingPoints;
private boolean trackDrawingEnabled; private boolean trackDrawingEnabled;
private int lastHeading = 0; private int lastHeading = 0;
private Location myLocation; private Location myLocation;
private boolean showEndMarker = true; private boolean showEndMarker = true;
private boolean drawBounds; // TODO: Remove it completely. If this is true, drawing is faster by 5%.
private boolean alwaysVisible = true;
/**
* Represents a pre-processed {@code Location} to speed up drawing.
*/
private static class CachedLocation {
public final boolean valid;
public final GeoPoint geoPoint;
public CachedLocation(Location location) {
this.valid = MyTracksUtils.isValidLocation(location);
this.geoPoint = valid ? MyTracksUtils.getGeoPoint(location) : null;
}
};
public MyTracksOverlay(Context context) { public MyTracksOverlay(Context context) {
this.context = context; this.context = context;
this.waypoints = new ArrayList<Waypoint>();
this.points = new ArrayList<CachedLocation>(256);
this.pendingPoints = new ArrayBlockingQueue<CachedLocation>(
MyTracksConstants.MAX_DISPLAYED_TRACK_POINTS, true);
// TODO: Can we use a FrameAnimation or similar here rather // TODO: Can we use a FrameAnimation or similar here rather
// than individual resources for each arrow direction? // than individual resources for each arrow direction?
final Resources resources = context.getResources();
arrow[0] = context.getResources().getDrawable(R.drawable.arrow_0); arrows = new Drawable[] {
arrow[1] = context.getResources().getDrawable(R.drawable.arrow_20); resources.getDrawable(R.drawable.arrow_0),
arrow[2] = context.getResources().getDrawable(R.drawable.arrow_40); resources.getDrawable(R.drawable.arrow_20),
arrow[3] = context.getResources().getDrawable(R.drawable.arrow_60); resources.getDrawable(R.drawable.arrow_40),
arrow[4] = context.getResources().getDrawable(R.drawable.arrow_80); resources.getDrawable(R.drawable.arrow_60),
arrow[5] = context.getResources().getDrawable(R.drawable.arrow_100); resources.getDrawable(R.drawable.arrow_80),
arrow[6] = context.getResources().getDrawable(R.drawable.arrow_120); resources.getDrawable(R.drawable.arrow_100),
arrow[7] = context.getResources().getDrawable(R.drawable.arrow_140); resources.getDrawable(R.drawable.arrow_120),
arrow[8] = context.getResources().getDrawable(R.drawable.arrow_160); resources.getDrawable(R.drawable.arrow_140),
arrow[9] = context.getResources().getDrawable(R.drawable.arrow_180); resources.getDrawable(R.drawable.arrow_160),
arrow[10] = context.getResources().getDrawable(R.drawable.arrow_200); resources.getDrawable(R.drawable.arrow_180),
arrow[11] = context.getResources().getDrawable(R.drawable.arrow_220); resources.getDrawable(R.drawable.arrow_200),
arrow[12] = context.getResources().getDrawable(R.drawable.arrow_240); resources.getDrawable(R.drawable.arrow_220),
arrow[13] = context.getResources().getDrawable(R.drawable.arrow_260); resources.getDrawable(R.drawable.arrow_240),
arrow[14] = context.getResources().getDrawable(R.drawable.arrow_280); resources.getDrawable(R.drawable.arrow_260),
arrow[15] = context.getResources().getDrawable(R.drawable.arrow_300); resources.getDrawable(R.drawable.arrow_280),
arrow[16] = context.getResources().getDrawable(R.drawable.arrow_320); resources.getDrawable(R.drawable.arrow_300),
arrow[17] = context.getResources().getDrawable(R.drawable.arrow_340); resources.getDrawable(R.drawable.arrow_320),
arrowWidth = arrow[lastHeading].getIntrinsicWidth(); resources.getDrawable(R.drawable.arrow_340)
arrowHeight = arrow[lastHeading].getIntrinsicHeight(); };
for (int i = 0; i <= 17; i++) { arrowWidth = arrows[lastHeading].getIntrinsicWidth();
arrow[i].setBounds(0, 0, arrowWidth, arrowHeight); arrowHeight = arrows[lastHeading].getIntrinsicHeight();
for (Drawable arrow : arrows) {
arrow.setBounds(0, 0, arrowWidth, arrowHeight);
} }
statsMarker = context.getResources().getDrawable(R.drawable.ylw_pushpin); statsMarker = resources.getDrawable(R.drawable.ylw_pushpin);
markerWidth = statsMarker.getIntrinsicWidth(); markerWidth = statsMarker.getIntrinsicWidth();
markerHeight = statsMarker.getIntrinsicHeight(); markerHeight = statsMarker.getIntrinsicHeight();
statsMarker.setBounds(0, 0, markerWidth, markerHeight); statsMarker.setBounds(0, 0, markerWidth, markerHeight);
startMarker = context.getResources().getDrawable(R.drawable.green_dot); startMarker = resources.getDrawable(R.drawable.green_dot);
startMarker.setBounds(0, 0, markerWidth, markerHeight); startMarker.setBounds(0, 0, markerWidth, markerHeight);
endMarker = context.getResources().getDrawable(R.drawable.red_dot); endMarker = resources.getDrawable(R.drawable.red_dot);
endMarker.setBounds(0, 0, markerWidth, markerHeight); endMarker.setBounds(0, 0, markerWidth, markerHeight);
waypointMarker = waypointMarker = resources.getDrawable(R.drawable.blue_pushpin);
context.getResources().getDrawable(R.drawable.blue_pushpin);
waypointMarker.setBounds(0, 0, markerWidth, markerHeight); waypointMarker.setBounds(0, 0, markerWidth, markerHeight);
selectedTrackPaint = new Paint(); selectedTrackPaint = new Paint();
selectedTrackPaint.setColor(context.getResources().getColor(R.color.red)); selectedTrackPaint.setColor(resources.getColor(R.color.red));
selectedTrackPaint.setStrokeWidth(3); selectedTrackPaint.setStrokeWidth(3);
selectedTrackPaint.setStyle(Paint.Style.STROKE); selectedTrackPaint.setStyle(Paint.Style.STROKE);
selectedTrackPaint.setAntiAlias(true); selectedTrackPaint.setAntiAlias(true);
errorCirclePaint = new Paint(); errorCirclePaint = new Paint();
errorCirclePaint.setColor(context.getResources().getColor(R.color.blue)); errorCirclePaint.setColor(resources.getColor(R.color.blue));
errorCirclePaint.setStyle(Paint.Style.STROKE); errorCirclePaint.setStyle(Paint.Style.STROKE);
errorCirclePaint.setStrokeWidth(3); errorCirclePaint.setStrokeWidth(3);
errorCirclePaint.setAlpha(127); errorCirclePaint.setAlpha(127);
@@ -124,35 +148,47 @@ public class MyTracksOverlay extends Overlay {
/** /**
* Add a location to the map overlay. * Add a location to the map overlay.
* *
* NOTE: this method takes ownership of this location and may change it. * NOTE: This method doesn't take ownership of the given location, so it is
* safe to reuse the same location while calling this method.
* *
* @param l the location to add * @param l the location to add.
*/ */
public void addLocation(Location l) { public void addLocation(Location l) {
if (l != null) { // Queue up in the pending queue until it's merged with {@code #points}.
synchronized (points) { pendingPoints.offer(new CachedLocation(l));
points.add(l);
}
}
} }
public void addWaypoint(Waypoint wpt) { public void addWaypoint(Waypoint wpt) {
if (wpt != null && wpt.getLocation() != null) {
synchronized (waypoints) {
waypoints.add(wpt); waypoints.add(wpt);
} }
}
}
public int getNumLocations() { public int getNumLocations() {
synchronized (points) { synchronized (points) {
return points.size(); return points.size() + pendingPoints.size();
} }
} }
public void clearWaypoints() { // Visible for testing.
waypoints.clear(); int getNumWaypoints() {
synchronized (waypoints) {
return waypoints.size();
}
} }
public void clearPoints() { public void clearPoints() {
synchronized (points) { synchronized (points) {
points.clear(); points.clear();
pendingPoints.clear();
}
}
public void clearWaypoints() {
synchronized (waypoints) {
waypoints.clear();
} }
} }
@@ -183,27 +219,13 @@ public class MyTracksOverlay extends Overlay {
} }
private void drawWaypoints(Canvas canvas, MapView mapView) { private void drawWaypoints(Canvas canvas, MapView mapView) {
ArrayList<Waypoint> currentWaypoints = waypoints; synchronized (waypoints) {;
for (int i = 1; i < currentWaypoints.size(); i++) { for (Waypoint wpt : waypoints) {
Waypoint wpt = currentWaypoints.get(i);
if (wpt == null) {
continue;
}
Location loc = wpt.getLocation(); Location loc = wpt.getLocation();
if (loc == null) { drawElement(canvas, mapView, MyTracksUtils.getGeoPoint(loc),
continue; wpt.getType() == Waypoint.TYPE_STATISTICS ? statsMarker
: waypointMarker, -(markerWidth / 2) + 3, -markerHeight);
} }
GeoPoint geoPoint = MyTracksUtils.getGeoPoint(loc);
Point pt = new Point();
mapView.getProjection().toPixels(geoPoint, pt);
canvas.save();
canvas.translate(pt.x - (markerWidth / 2) + 3, pt.y - (markerHeight));
if (wpt.getType() == Waypoint.TYPE_STATISTICS) {
statsMarker.draw(canvas);
} else {
waypointMarker.draw(canvas);
}
canvas.restore();
} }
} }
@@ -213,16 +235,9 @@ public class MyTracksOverlay extends Overlay {
return; return;
} }
GeoPoint geoPoint = new GeoPoint( Point pt = drawElement(canvas, mapView,
(int) (myLocation.getLatitude() * 1E6), MyTracksUtils.getGeoPoint(myLocation), arrows[lastHeading],
(int) (myLocation.getLongitude() * 1E6)); -(arrowWidth / 2) + 3, -(arrowHeight / 2));
Point pt = new Point();
mapView.getProjection().toPixels(geoPoint, pt);
canvas.save();
canvas.translate(pt.x - (arrowWidth / 2), pt.y - (arrowHeight / 2));
arrow[lastHeading].draw(canvas);
canvas.restore();
// Draw the error circle: // Draw the error circle:
float radius = float radius =
mapView.getProjection().metersToEquatorPixels(myLocation.getAccuracy()); mapView.getProjection().metersToEquatorPixels(myLocation.getAccuracy());
@@ -230,170 +245,92 @@ public class MyTracksOverlay extends Overlay {
} }
private void drawTrack(Canvas canvas, MapView mapView) { private void drawTrack(Canvas canvas, MapView mapView) {
Path path;
Point pt = new Point();
Location lastValidLocation;
int locLon = 0, locLat = 0;
GeoPoint firstGeoPoint = null; GeoPoint firstGeoPoint = null;
boolean lastLocValid; GeoPoint lastGeoPoint = null;
// Get the current viewing window: // Get the current viewing window.
Rect viewRect = null;
if (!alwaysVisible) {
int w = mapView.getLongitudeSpan(); int w = mapView.getLongitudeSpan();
int h = mapView.getLatitudeSpan(); int h = mapView.getLatitudeSpan();
int cx = mapView.getMapCenter().getLongitudeE6(); int cx = mapView.getMapCenter().getLongitudeE6();
int cy = mapView.getMapCenter().getLatitudeE6(); int cy = mapView.getMapCenter().getLatitudeE6();
Rect viewRect = new Rect(cx - w, cy - h, cx + w, cy + h); viewRect = new Rect(cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2);
}
// Global bounding box, including points not visible
int allMinLat, allMinLon, allMaxLat, allMaxLon;
final Path path = new Path();
final Point pt = new Point();
synchronized (points) { synchronized (points) {
// Merge the pending points with the list of cached locations.
pendingPoints.drainTo(points);
int numPoints = points.size(); int numPoints = points.size();
if (numPoints < 2) { if (numPoints < 2) {
return; return;
} }
GeoPoint geoPoint;
Location loc;
int minLon, maxLon, minLat, maxLat;
lastValidLocation = points.get(0);
int lastLocLon = allMinLon = allMaxLon = (int) (lastValidLocation.getLongitude() * 1E6);
int lastLocLat = allMinLat = allMaxLat = (int) (lastValidLocation.getLatitude() * 1E6);
lastLocValid = MyTracksUtils.isValidLocation(lastValidLocation);
boolean lastLocVisible = false;
path = new Path();
// Loop over track points:
path.incReserve(numPoints); path.incReserve(numPoints);
for (int i = 1; i < numPoints; i++) {
loc = points.get(i);
boolean locValid = MyTracksUtils.isValidLocation(loc); // Whether to start a new segment on new valid and visible point.
boolean locVisible = false; boolean newSegment = true;
if (locValid) { boolean lastVisible = false;
locLon = (int) (loc.getLongitude() * 1E6); // Loop over track points:
locLat = (int) (loc.getLatitude() * 1E6); for (CachedLocation loc : points) {
// Check if valid, if not then indicate a new segment.
if (!loc.valid) {
newSegment = true;
continue;
}
final GeoPoint geoPoint = loc.geoPoint;
if (firstGeoPoint == null) { if (firstGeoPoint == null) {
// Found the starting point // Found the starting point.
firstGeoPoint = new GeoPoint(locLat, locLon); firstGeoPoint = geoPoint;
} }
lastGeoPoint = geoPoint;
// If both the current and previous locations were valid // Check if break the existing segment.
if (lastLocValid) { boolean visible = alwaysVisible || viewRect.contains(
lastValidLocation = loc; geoPoint.getLongitudeE6(), geoPoint.getLatitudeE6());
if (!visible && !lastVisible) {
// Get the bounding box of the segment about to be drawn // So this is a point outside view not connected to a visible one.
if (locLon > lastLocLon) { newSegment = true;
minLon = lastLocLon;
maxLon = locLon;
} else {
minLon = locLon;
maxLon = lastLocLon;
}
if (locLat > lastLocLat) {
minLat = lastLocLat;
maxLat = locLat;
} else {
minLat = locLat;
maxLat = lastLocLat;
} }
lastVisible = visible;
if (drawBounds) { // Either move to beginning of a new segment or continue the old one.
allMaxLat = Math.max(allMaxLat, maxLat);
allMinLat = Math.min(allMinLat, minLat);
allMaxLon = Math.max(allMaxLon, maxLon);
allMinLon = Math.min(allMinLon, minLon);
}
// See if that bounding box intersects the viewable bounding box
// Assume that if it does, the location is visible
locVisible = viewRect.intersects(minLon, minLat, maxLon, maxLat);
if (locVisible) {
// If the previous point wasn't drawn, start at its position
if (!lastLocVisible) {
geoPoint = new GeoPoint(lastLocLat, lastLocLon);
mapView.getProjection().toPixels(geoPoint, pt); mapView.getProjection().toPixels(geoPoint, pt);
if (newSegment) {
path.moveTo(pt.x, pt.y); path.moveTo(pt.x, pt.y);
} newSegment = false;
} else {
// Draw a line to the new point
geoPoint = new GeoPoint(locLat, locLon);
mapView.getProjection().toPixels(geoPoint, pt);
path.lineTo(pt.x, pt.y); path.lineTo(pt.x, pt.y);
} }
} }
} }
lastLocLon = locLon;
lastLocLat = locLat;
lastLocValid = locValid;
lastLocVisible = locVisible;
}
}
canvas.drawPath(path, selectedTrackPaint); canvas.drawPath(path, selectedTrackPaint);
if (drawBounds) { // Draw the "End" marker.
drawBoundingBox(canvas, mapView, if (showEndMarker && lastGeoPoint != null) {
allMinLat, allMinLon, allMaxLat, allMaxLon); drawElement(canvas, mapView, lastGeoPoint, endMarker, -markerWidth / 2,
} -markerHeight);
// Draw the "End" marker:
if (showEndMarker && lastValidLocation != null) {
canvas.save();
GeoPoint geoPoint = MyTracksUtils.getGeoPoint(lastValidLocation);
mapView.getProjection().toPixels(geoPoint, pt);
canvas.translate(pt.x - (markerWidth / 2), pt.y - markerHeight);
endMarker.draw(canvas);
canvas.restore();
} }
// Draw the "Start" marker: // Draw the "Start" marker:
if (firstGeoPoint != null) { if (firstGeoPoint != null) {
mapView.getProjection().toPixels(firstGeoPoint, pt); drawElement(canvas, mapView, firstGeoPoint, startMarker, -markerWidth / 2,
-markerHeight);
}
}
private Point drawElement(Canvas canvas, MapView mapView, GeoPoint geoPoint,
Drawable element, int offsetX, int offsetY) {
Point pt = new Point();
mapView.getProjection().toPixels(geoPoint, pt);
canvas.save(); canvas.save();
canvas.translate(pt.x - (markerWidth / 2), pt.y - markerHeight); canvas.translate(pt.x + offsetX, pt.y + offsetY);
startMarker.draw(canvas); element.draw(canvas);
canvas.restore(); canvas.restore();
} return pt;
}
private void drawBoundingBox(Canvas canvas, MapView mapView, int allMinLat,
int allMinLon, int allMaxLat, int allMaxLon) {
// Transform coordinates
GeoPoint maxPoint = new GeoPoint(allMaxLat, allMaxLon);
GeoPoint minPoint = new GeoPoint(allMinLat, allMinLon);
Point minPt = new Point();
Point maxPt = new Point();
mapView.getProjection().toPixels(minPoint, minPt);
mapView.getProjection().toPixels(maxPoint, maxPt);
Rect allBounds = new Rect(minPt.x, minPt.y, maxPt.x, maxPt.y);
// Prepare a green paint
Paint boundingBoxPaint = new Paint();
boundingBoxPaint.setColor(context.getResources().getColor(R.color.green));
boundingBoxPaint.setStrokeWidth(2);
boundingBoxPaint.setStyle(Paint.Style.STROKE);
boundingBoxPaint.setAntiAlias(true);
// Disable clipping
canvas.save();
canvas.clipRect(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY,
Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY,
Region.Op.REPLACE);
// Draw the bounding box
canvas.drawRect(allBounds, boundingBoxPaint);
// Re-enable clipping
canvas.restore();
}
@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
draw(canvas, mapView, shadow);
return false;
} }
/** /**
@@ -436,6 +373,7 @@ public class MyTracksOverlay extends Overlay {
final Location tapLocation = MyTracksUtils.getLocation(p); final Location tapLocation = MyTracksUtils.getLocation(p);
double dmin = Double.MAX_VALUE; double dmin = Double.MAX_VALUE;
Waypoint waypoint = null; Waypoint waypoint = null;
synchronized (waypoints) {
for (int i = 0; i < waypoints.size(); i++) { for (int i = 0; i < waypoints.size(); i++) {
final Location waypointLocation = waypoints.get(i).getLocation(); final Location waypointLocation = waypoints.get(i).getLocation();
if (waypointLocation == null) { if (waypointLocation == null) {
@@ -447,9 +385,10 @@ public class MyTracksOverlay extends Overlay {
waypoint = waypoints.get(i); waypoint = waypoints.get(i);
} }
} }
}
if (waypoint != null if (waypoint != null &&
&& dmin < 15000000 / Math.pow(2, mapView.getZoomLevel())) { dmin < 15000000 / Math.pow(2, mapView.getZoomLevel())) {
Intent intent = new Intent(context, MyTracksWaypointDetails.class); Intent intent = new Intent(context, MyTracksWaypointDetails.class);
intent.putExtra("waypointid", waypoint.getId()); intent.putExtra("waypointid", waypoint.getId());
context.startActivity(intent); context.startActivity(intent);
@@ -457,8 +396,4 @@ public class MyTracksOverlay extends Overlay {
} }
return super.onTap(p, mapView); return super.onTap(p, mapView);
} }
public void setDrawBounds(boolean drawBounds) {
this.drawBounds = drawBounds;
}
} }
@@ -0,0 +1,133 @@
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.maps.MapView;
import android.graphics.Canvas;
import android.location.Location;
import android.test.AndroidTestCase;
/**
* Tests for the MyTracks map overlay.
*
* @author Bartlomiej Niechwiej
*/
public class MyTracksOverlayTest extends AndroidTestCase {
private Canvas canvas;
private MyTracksOverlay myTracksOverlay;
private MapView mockView;
@Override
protected void setUp() throws Exception {
super.setUp();
canvas = new Canvas();
myTracksOverlay = new MyTracksOverlay(getContext());
// TODO: add real mock view and enable track drawing.
mockView = null;
}
public void testAddLocation() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
myTracksOverlay.addLocation(location);
assertEquals(1, myTracksOverlay.getNumLocations());
location.setLatitude(20);
location.setLongitude(30);
myTracksOverlay.addLocation(location);
assertEquals(2, myTracksOverlay.getNumLocations());
// Draw and make sure that we don't lose any point.
myTracksOverlay.draw(canvas, mockView, false);
assertEquals(2, myTracksOverlay.getNumLocations());
myTracksOverlay.draw(canvas, mockView, true);
assertEquals(2, myTracksOverlay.getNumLocations());
}
public void testClearPoints() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
myTracksOverlay.addLocation(location);
assertEquals(1, myTracksOverlay.getNumLocations());
myTracksOverlay.clearPoints();
assertEquals(0, myTracksOverlay.getNumLocations());
// Same after drawing on canvas.
final int locations = 100;
for (int i = 0; i < locations; ++i) {
myTracksOverlay.addLocation(location);
}
assertEquals(locations, myTracksOverlay.getNumLocations());
myTracksOverlay.draw(canvas, mockView, false);
myTracksOverlay.draw(canvas, mockView, true);
myTracksOverlay.clearPoints();
assertEquals(0, myTracksOverlay.getNumLocations());
}
public void testAddWaypoint() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
Waypoint waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
assertEquals(1, myTracksOverlay.getNumWaypoints());
final int waypoints = 10;
for (int i = 0; i < waypoints; ++i) {
waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
}
assertEquals(1 + waypoints, myTracksOverlay.getNumWaypoints());
}
public void testClearWaypoints() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
Waypoint waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
assertEquals(1, myTracksOverlay.getNumWaypoints());
myTracksOverlay.clearWaypoints();
assertEquals(0, myTracksOverlay.getNumWaypoints());
}
public void testDrawing() {
Location location = new Location("gps");
location.setLatitude(10);
for (int i = 0; i < 40; ++i) {
location.setLongitude(20 + i);
Waypoint waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
}
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(50 + i);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
}
myTracksOverlay.draw(canvas, mockView, false);
myTracksOverlay.draw(canvas, mockView, true);
}
}