2 * Copyright © 2010 Anthony Towns <aj@erisian.com.au>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; version 2 of the License.
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
18 package org.altusmetrum.altosuilib_2;
21 import java.awt.event.*;
24 import java.lang.Math;
25 import java.awt.geom.*;
27 import java.util.concurrent.*;
28 import org.altusmetrum.altoslib_4.*;
34 public MapPoint(double lat, double lon, int state) {
40 public boolean equals(MapPoint other) {
47 if (other.state != state)
53 public class AltosSiteMap extends JComponent implements AltosFlightDisplay, MouseMotionListener, MouseListener, HierarchyBoundsListener {
54 // preferred vertical step in a tile in naut. miles
55 // will actually choose a step size between x and 2x, where this
57 static final double tile_size_nmi = 0.75;
59 static final int px_size = 512;
61 static final int MAX_TILE_DELTA = 100;
63 static final int maptype_hybrid = 0;
64 static final int maptype_roadmap = 1;
65 static final int maptype_satellite = 2;
66 static final int maptype_terrain = 3;
68 int maptype = maptype_hybrid;
70 static final String[] maptype_names = {
77 static final String[] maptype_labels = {
84 LinkedList<MapPoint> points = new LinkedList<MapPoint>();
86 private static Point2D.Double translatePoint(Point2D.Double p,
89 return new Point2D.Double(p.x + d.x, p.y + d.y);
93 public double lat, lng;
94 public LatLng(double lat, double lng) {
100 // based on google js
101 // http://maps.gstatic.com/intl/en_us/mapfiles/api-3/2/10/main.js
102 // search for fromLatLngToPoint and fromPointToLatLng
104 private static Point2D.Double pt(LatLng latlng, int zoom) {
105 double scale_x = 256/360.0 * Math.pow(2, zoom);
106 double scale_y = 256/(2.0*Math.PI) * Math.pow(2, zoom);
107 return pt(latlng, scale_x, scale_y);
111 private static Point2D.Double pt(LatLng latlng,
112 double scale_x, double scale_y)
114 Point2D.Double res = new Point2D.Double();
117 res.x = latlng.lng * scale_x;
119 e = Math.sin(Math.toRadians(latlng.lat));
120 e = Math.max(e,-(1-1.0E-15));
121 e = Math.min(e, 1-1.0E-15 );
123 res.y = 0.5*Math.log((1+e)/(1-e))*-scale_y;
127 static private LatLng latlng(Point2D.Double pt,
128 double scale_x, double scale_y)
134 rads = 2 * Math.atan(Math.exp(-pt.y/scale_y));
135 lat = Math.toDegrees(rads - Math.PI/2);
137 return new LatLng(lat,lng);
140 static final int default_zoom = 15;
141 static final int min_zoom = 3;
142 static final int max_zoom = 21;
144 int zoom = default_zoom;
146 double scale_x, scale_y;
148 int radius; /* half width/height of tiles to load */
150 private Point2D.Double pt(double lat, double lng) {
151 return pt(new LatLng(lat, lng), scale_x, scale_y);
154 private LatLng latlng(double x, double y) {
155 return latlng(new Point2D.Double(x,y), scale_x, scale_y);
158 private LatLng latlng(Point2D.Double pt) {
159 return latlng(pt, scale_x, scale_y);
163 private LatLng latlng(Point pt) {
164 return latlng(new Point2D.Double(pt.x, pt.y), scale_x, scale_y);
167 ConcurrentHashMap<Point,AltosSiteMapTile> mapTiles = new ConcurrentHashMap<Point,AltosSiteMapTile>();
168 Point2D.Double centre;
170 private Point2D.Double tileCoordOffset(Point p) {
171 return new Point2D.Double(centre.x - p.x*px_size,
172 centre.y - p.y*px_size);
175 private Point tileOffset(Point2D.Double p) {
176 return new Point((int)Math.floor((centre.x+p.x)/px_size),
177 (int)Math.floor((centre.y+p.y)/px_size));
180 private Point2D.Double getBaseLocation(double lat, double lng) {
181 Point2D.Double locn = pt(0,0), north_step;
183 scale_x = 256/360.0 * Math.pow(2, zoom);
184 scale_y = 256/(2.0*Math.PI) * Math.pow(2, zoom);
186 locn.x = -px_size * Math.floor(locn.x/px_size);
187 locn.y = -px_size * Math.floor(locn.y/px_size);
191 public void reset() {
195 public void set_font() {
196 for (AltosSiteMapTile tile : mapTiles.values())
197 tile.set_font(AltosUILib.value_font);
200 static final int load_mode_cached = 1;
201 static final int load_mode_uncached = 2;
203 private boolean load_map(final AltosSiteMapTile tile,
204 final File pngfile, String pngurl,
207 boolean has_map = AltosSiteMapCache.has_map(pngfile, pngurl);
208 if ((load_mode & load_mode_uncached) == 0 && !has_map)
210 if ((load_mode & load_mode_cached) == 0 && has_map)
213 tile.set_status(AltosSiteMapCache.loading);
214 int status = AltosSiteMapCache.fetch_map(pngfile, pngurl);
215 if (status == AltosSiteMapCache.success) {
216 if (SwingUtilities.isEventDispatchThread())
217 tile.load_map(pngfile);
219 SwingUtilities.invokeLater(new Runnable() {
221 tile.load_map(pngfile);
226 tile.set_status(status);
227 System.out.printf("# Failed to fetch file %s (status %d)\n", pngfile, status);
228 System.out.printf(" wget -O '%s' '%s'\n", pngfile, pngurl);
229 System.out.printf(" sleep 1\n");
235 class AltosSiteMapPrefetch {
243 public AltosSiteMapPrefetch prefetchMap(int x, int y) {
244 AltosSiteMapPrefetch prefetch = new AltosSiteMapPrefetch();
245 LatLng map_latlng = latlng(
246 -centre.x + x*px_size + px_size/2,
247 -centre.y + y*px_size + px_size/2);
248 prefetch.pngfile = MapFile(map_latlng.lat, map_latlng.lng, zoom, maptype_hybrid);
249 prefetch.pngurl = MapURL(map_latlng.lat, map_latlng.lng, zoom, maptype_hybrid);
250 if (AltosSiteMapCache.has_map(prefetch.pngfile, prefetch.pngurl)) {
252 } else if (AltosSiteMapCache.fetch_map(prefetch.pngfile, prefetch.pngurl) == AltosSiteMapCache.success) {
255 prefetch.result = -1;
260 public static void prefetchMaps(double lat, double lng) {
261 int w = AltosSiteMapPreload.width;
262 int h = AltosSiteMapPreload.height;
263 AltosSiteMap asm = new AltosSiteMap(true);
264 asm.centre = asm.getBaseLocation(lat, lng);
266 //Point2D.Double p = new Point2D.Double();
268 int dx = -w/2, dy = -h/2;
269 for (int y = dy; y < h+dy; y++) {
270 for (int x = dx; x < w+dx; x++) {
271 AltosSiteMapPrefetch prefetch = asm.prefetchMap(x, y);
272 switch (prefetch.result) {
274 System.out.printf("Already have %s\n", prefetch.pngfile);
277 System.out.printf("Fetched map %s\n", prefetch.pngfile);
280 System.out.printf("# Failed to fetch file %s\n", prefetch.pngfile);
281 System.out.printf(" wget -O '%s' ''\n",
282 prefetch.pngfile, prefetch.pngurl);
289 public File init_map(Point offset, int load_mode) {
290 AltosSiteMapTile tile = mapTiles.get(offset);
291 Point2D.Double coord = tileCoordOffset(offset);
293 LatLng map_latlng = latlng(px_size/2-coord.x, px_size/2-coord.y);
295 File pngfile = MapFile(map_latlng.lat, map_latlng.lng, zoom, maptype);
296 String pngurl = MapURL(map_latlng.lat, map_latlng.lng, zoom, maptype);
297 load_map(tile, pngfile, pngurl, load_mode);
301 public void initAndFinishMapAsync (final AltosSiteMapTile tile, final Point offset) {
302 Thread thread = new Thread() {
304 init_map(offset, load_mode_cached|load_mode_uncached);
305 SwingUtilities.invokeLater( new Runnable() {
307 addTileAt(tile, offset);
316 boolean base_location_set = false;
318 public void clear_base_location() {
319 base_location_set = false;
321 points = new LinkedList<MapPoint>();
322 line_start = line_end = null;
325 public void setBaseLocation(double lat, double lng) {
328 base_location_set = true;
330 centre = getBaseLocation(lat, lng);
331 scrollRocketToVisible(pt(lat,lng));
334 private void initMaps(double lat, double lng) {
335 setBaseLocation(lat, lng);
337 for (AltosSiteMapTile tile : mapTiles.values())
339 Thread thread = new Thread() {
341 for (Point k : mapTiles.keySet())
342 init_map(k, load_mode_cached);
343 for (Point k : mapTiles.keySet())
344 init_map(k, load_mode_uncached);
350 private static File MapFile(double lat, double lng, int zoom, int maptype) {
351 char chlat = lat < 0 ? 'S' : 'N';
352 char chlng = lng < 0 ? 'W' : 'E';
353 if (lat < 0) lat = -lat;
354 if (lng < 0) lng = -lng;
355 String maptype_string = String.format("%s-", maptype_names[maptype]);
356 String format_string;
357 if (maptype == maptype_hybrid || maptype == maptype_satellite || maptype == maptype_terrain)
358 format_string = "jpg";
360 format_string = "png";
361 return new File(AltosUIPreferences.mapdir(),
362 String.format("map-%c%.6f,%c%.6f-%s%d.%s",
363 chlat, lat, chlng, lng, maptype_string, zoom, format_string));
366 private static String MapURL(double lat, double lng, int zoom, int maptype) {
367 String format_string;
368 if (maptype == maptype_hybrid || maptype == maptype_satellite || maptype == maptype_terrain)
369 format_string = "jpg";
371 format_string = "png32";
372 return String.format("http://maps.google.com/maps/api/staticmap?center=%.6f,%.6f&zoom=%d&size=%dx%d&sensor=false&maptype=%s&format=%s",
373 lat, lng, zoom, px_size, px_size, maptype_names[maptype], format_string);
376 boolean initialised = false;
377 MapPoint last_point = null;
380 public void show(double lat, double lon) {
381 System.out.printf ("show %g %g\n", lat, lon);
383 // initMaps(lat, lon);
384 // scrollRocketToVisible(pt(lat, lon));
389 public void set_zoom_label() {
390 zoom_label.setText(String.format("Zoom %d", zoom - default_zoom));
393 public void set_zoom(int zoom) {
394 if (min_zoom <= zoom && zoom <= max_zoom) {
396 if (base_location_set)
403 public int get_zoom() {
407 public void draw(MapPoint last_point, MapPoint point) {
408 boolean force_ensure = false;
409 if (last_point == null) {
414 Point2D.Double pt = pt(point.lat, point.lon);
415 Point2D.Double last_pt = pt(last_point.lat, last_point.lon);
417 boolean in_any = false;
418 for (Point offset : mapTiles.keySet()) {
419 AltosSiteMapTile tile = mapTiles.get(offset);
420 Point2D.Double ref, lref;
421 ref = translatePoint(pt, tileCoordOffset(offset));
422 lref = translatePoint(last_pt, tileCoordOffset(offset));
423 tile.show(point.state, lref, ref);
424 if (0 <= ref.x && ref.x < px_size)
425 if (0 <= ref.y && ref.y < px_size)
429 Point offset = tileOffset(pt);
431 Point2D.Double ref, lref;
432 ref = translatePoint(pt, tileCoordOffset(offset));
433 lref = translatePoint(last_pt, tileCoordOffset(offset));
435 AltosSiteMapTile tile = createTile(offset);
436 tile.show(point.state, lref, ref);
437 initAndFinishMapAsync(tile, offset);
440 scrollRocketToVisible(pt);
442 if (force_ensure || offset != tileOffset(last_pt)) {
443 ensureTilesAround(offset);
447 public void redraw() {
448 MapPoint last_point = null;
450 for (MapPoint point : points) {
451 draw(last_point, point);
455 draw_circle(circle_lat, circle_lon);
456 if (line_start != null)
460 public void show(final AltosState state, final AltosListenerState listener_state) {
461 // if insufficient gps data, nothing to update
462 AltosGPS gps = state.gps;
467 if (!gps.locked && gps.nsat < 4)
471 if (state.pad_lat != AltosLib.MISSING && state.pad_lon != AltosLib.MISSING) {
472 initMaps(state.pad_lat, state.pad_lon);
474 } else if (gps.lat != AltosLib.MISSING && gps.lon != AltosLib.MISSING) {
475 initMaps(gps.lat, gps.lon);
482 MapPoint point = new MapPoint(gps.lat, gps.lon, state.state);
484 if (point.equals(last_point))
489 draw(last_point, point);
494 public void centre(Point2D.Double pt) {
495 Rectangle r = comp.getVisibleRect();
496 Point2D.Double copt = translatePoint(pt, tileCoordOffset(topleft));
497 int dx = (int)copt.x - r.width/2 - r.x;
498 int dy = (int)copt.y - r.height/2 - r.y;
503 comp.scrollRectToVisible(r);
506 public void centre(AltosState state) {
507 if (!state.gps.locked && state.gps.nsat < 4)
509 centre(pt(state.gps.lat, state.gps.lon));
512 private double circle_lat, circle_lon;
513 private boolean circle_set = false;
515 public void draw_circle(double lat, double lon) {
520 Point2D.Double pt = pt(lat, lon);
522 for (Point offset : mapTiles.keySet()) {
523 AltosSiteMapTile tile = mapTiles.get(offset);
524 Point2D.Double ref = translatePoint(pt, tileCoordOffset(offset));
529 private AltosSiteMapTile createTile(Point offset) {
530 AltosSiteMapTile tile = new AltosSiteMapTile(px_size);
531 tile.set_font(AltosUILib.value_font);
532 mapTiles.put(offset, tile);
536 private void ensureTilesAround(Point base_offset) {
537 for (int x = -radius; x <= radius; x++) {
538 for (int y = -radius; y <= radius; y++) {
539 Point offset = new Point(base_offset.x + x, base_offset.y + y);
540 if (mapTiles.containsKey(offset))
542 AltosSiteMapTile tile = createTile(offset);
543 initAndFinishMapAsync(tile, offset);
548 private Point topleft = new Point(0,0);
549 private void scrollRocketToVisible(Point2D.Double pt) {
550 Rectangle r = comp.getVisibleRect();
551 Point2D.Double copt = translatePoint(pt, tileCoordOffset(topleft));
553 int dx = (int)copt.x - r.width/2 - r.x;
554 int dy = (int)copt.y - r.height/2 - r.y;
555 if (Math.abs(dx) > r.width/4 || Math.abs(dy) > r.height/4) {
558 comp.scrollRectToVisible(r);
562 private void addTileAt(AltosSiteMapTile tile, Point offset) {
563 if (Math.abs(offset.x) >= MAX_TILE_DELTA ||
564 Math.abs(offset.y) >= MAX_TILE_DELTA)
566 System.out.printf("Rocket too far away from pad (tile %d,%d)\n",
571 boolean review = false;
572 Rectangle r = comp.getVisibleRect();
573 if (offset.x < topleft.x) {
574 r.x += (topleft.x - offset.x) * px_size;
575 topleft.x = offset.x;
578 if (offset.y < topleft.y) {
579 r.y += (topleft.y - offset.y) * px_size;
580 topleft.y = offset.y;
583 GridBagConstraints c = new GridBagConstraints();
584 c.anchor = GridBagConstraints.CENTER;
585 c.fill = GridBagConstraints.BOTH;
586 // put some space between the map tiles, debugging only
587 // c.insets = new Insets(5, 5, 5, 5);
589 c.gridx = offset.x + MAX_TILE_DELTA;
590 c.gridy = offset.y + MAX_TILE_DELTA;
591 layout.setConstraints(tile, c);
595 // comp.scrollRectToVisible(r);
599 private AltosSiteMap(boolean knowWhatYouAreDoing) {
600 if (!knowWhatYouAreDoing) {
601 throw new RuntimeException("Arggh.");
607 private GridBagLayout layout = new GridBagLayout();
609 LatLng line_start, line_end;
611 private void set_line() {
612 if (line_start != null && line_end != null) {
613 Point2D.Double start = pt(line_start.lat, line_start.lng);
614 Point2D.Double end = pt(line_end.lat, line_end.lng);
615 AltosGreatCircle g = new AltosGreatCircle(line_start.lat, line_start.lng,
616 line_end.lat, line_end.lng);
618 for (Point offset : mapTiles.keySet()) {
619 AltosSiteMapTile tile = mapTiles.get(offset);
621 s = translatePoint(start, tileCoordOffset(offset));
622 e = translatePoint(end, tileCoordOffset(offset));
623 tile.set_line(new Line2D.Double(s.x, s.y, e.x, e.y), g.distance);
626 for (AltosSiteMapTile tile : mapTiles.values())
627 tile.set_line(null, 0);
631 static void debug_component(Component who, String where) {
632 // Rectangle r = who.getBounds();
633 // int x = r.x / px_size;
634 // int y = r.y / px_size;
636 // System.out.printf ("%3d, %3d: %s\n", x, y, where);
639 LatLng latlng(MouseEvent e) {
640 if (!base_location_set)
643 Rectangle zerozero = mapTiles.get(new Point(0, 0)).getBounds();
645 return latlng(-centre.x + e.getPoint().x - zerozero.x, -centre.y + e.getPoint().y - zerozero.y);
648 /* MouseMotionListener methods */
649 public void mouseDragged(MouseEvent e) {
650 if (!GrabNDrag.grab_n_drag(e)) {
651 LatLng loc = latlng(e);
657 public void mouseMoved(MouseEvent e) {
660 /* MouseListener methods */
661 public void mouseClicked(MouseEvent e) {
664 public void mouseEntered(MouseEvent e) {
667 public void mouseExited(MouseEvent e) {
670 public void mousePressed(MouseEvent e) {
671 if (!GrabNDrag.grab_n_drag(e)) {
672 LatLng loc = latlng(e);
679 public void mouseReleased(MouseEvent e) {
682 public void set_cache_size() {
683 Rectangle r = comp.getVisibleRect();
685 int width_tiles = (r.width + 2*px_size) / px_size;
686 int height_tiles = (r.height + 2*px_size) / px_size;
687 int tiles = width_tiles * height_tiles;
688 AltosSiteMapCache.set_cache_size(tiles);
691 /* HierarchyBoundsListener methods */
692 public void ancestorMoved(HierarchyEvent e) {
696 public void ancestorResized(HierarchyEvent e) {
700 JScrollPane pane = new JScrollPane();
702 public AltosSiteMap(int in_radius) {
705 comp = new JComponent() { };
707 comp.addMouseMotionListener(this);
708 comp.addMouseListener(this);
709 comp.addHierarchyBoundsListener(this);
711 GrabNDrag scroller = new GrabNDrag(comp);
713 comp.setLayout(layout);
715 for (int x = -radius; x <= radius; x++) {
716 for (int y = -radius; y <= radius; y++) {
717 Point offset = new Point(x, y);
718 AltosSiteMapTile t = createTile(offset);
719 addTileAt(t, offset);
722 pane.setViewportView(comp);
723 pane.setPreferredSize(new Dimension(500,500));
724 pane.setVisible(true);
725 pane.setEnabled(true);
727 GridBagLayout my_layout = new GridBagLayout();
729 setLayout(my_layout);
731 GridBagConstraints c = new GridBagConstraints();
732 c.anchor = GridBagConstraints.CENTER;
733 c.fill = GridBagConstraints.BOTH;
744 zoom_label = new JLabel("", JLabel.CENTER);
747 c = new GridBagConstraints();
748 c.anchor = GridBagConstraints.CENTER;
749 c.fill = GridBagConstraints.HORIZONTAL;
756 JButton zoom_reset = new JButton("0");
757 zoom_reset.addActionListener(new ActionListener() {
758 public void actionPerformed(ActionEvent e) {
759 set_zoom(default_zoom);
763 c = new GridBagConstraints();
764 c.anchor = GridBagConstraints.CENTER;
765 c.fill = GridBagConstraints.HORIZONTAL;
772 JButton zoom_in = new JButton("+");
773 zoom_in.addActionListener(new ActionListener() {
774 public void actionPerformed(ActionEvent e) {
775 set_zoom(get_zoom() + 1);
779 c = new GridBagConstraints();
780 c.anchor = GridBagConstraints.CENTER;
781 c.fill = GridBagConstraints.HORIZONTAL;
788 JButton zoom_out = new JButton("-");
789 zoom_out.addActionListener(new ActionListener() {
790 public void actionPerformed(ActionEvent e) {
791 set_zoom(get_zoom() - 1);
794 c = new GridBagConstraints();
795 c.anchor = GridBagConstraints.CENTER;
796 c.fill = GridBagConstraints.HORIZONTAL;
803 final JComboBox<String> maptype_combo = new JComboBox<String>(maptype_labels);
805 maptype_combo.setEditable(false);
806 maptype_combo.setMaximumRowCount(maptype_combo.getItemCount());
807 maptype_combo.addItemListener(new ItemListener() {
808 public void itemStateChanged(ItemEvent e) {
809 maptype = maptype_combo.getSelectedIndex();
810 if (base_location_set)
816 c = new GridBagConstraints();
817 c.anchor = GridBagConstraints.CENTER;
818 c.fill = GridBagConstraints.HORIZONTAL;
823 add(maptype_combo, c);
826 public AltosSiteMap() {