Code:
public class ScaleBarComponent implements MapComponent {
private MapDisplay map;
private static final String ID = "ScaleBar";
private static final String VERSION = "1.0";
private int y_coord;
private int x_coord_start;
private int x_coord_end;
private String text = "";
final static int[] SCALE_IN_METRES = new int[]{5000000, 2000000, 1000000,
600000, 300000, 150000, 75000, 30000, 20000, 10000, 5000, 2000, 1000,
500, 250, 100, 50, 25};
final static String[] SCALE_IN_METRES_TEXT = new String[]{"5000km", "2000km", "1000km",
"600km", "300km", "150km", "75km", "30km", "20km", "10km", "5km", "2km", "1km",
"500m", "250m", "100m", "50m", "25m"};
/**
* Attaches a Map to the Map Component.
* @param map
*/
public void attach(MapDisplay map) {
this.map = map;
}
// from MapComponent
public void detach(MapDisplay map) {
this.map = null;
}
// from MapComponent
public String getId() {
return ID;
}
// from MapComponent
public String getVersion() {
return VERSION;
}
// from MapComponent
public EventListener getEventListener() {
return null;
}
/**
* When the map is updated, we need to recalculate the length of the bar.
* @param zoomChanged
*/
public void mapUpdated(boolean zoomChanged) {
x_coord_end = map.getWidth() - 20;
y_coord = map.getHeight() - 20;
double zoom = map.getZoomLevel();
zoom = (zoom >= map.getMinZoomLevel()) ? zoom : map.getMinZoomLevel();
if (zoom <= SCALE_IN_METRES.length - 1) {
GeoCoordinate end = map.pixelToGeo(new Point(x_coord_end, y_coord));
x_coord_start = x_coord_end - 10;
while (map.pixelToGeo(new Point(x_coord_start, y_coord)).distanceTo(end) < SCALE_IN_METRES[(int) zoom]) {
x_coord_start--;
}
text = SCALE_IN_METRES_TEXT[(int) zoom];
}
}
public void paint(Graphics g) {
//
g.drawLine(x_coord_start, y_coord, x_coord_end, y_coord);
g.drawLine(x_coord_start, y_coord + 2, x_coord_start, y_coord);
g.drawLine(x_coord_end, y_coord + 2, x_coord_end, y_coord);
g.drawString(
text, x_coord_end, y_coord, Graphics.BOTTOM | Graphics.
RIGHT);
}
}
You could do something similar for a Compass, just add an image over the map instead.