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 public 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 font_size_changed(int font_size) {
196 for (AltosSiteMapTile tile : mapTiles.values())
197 tile.set_font(AltosUILib.value_font);
200 public void units_changed(boolean imperial_units) {
204 static final int load_mode_cached = 1;
205 static final int load_mode_uncached = 2;
207 private boolean load_map(final AltosSiteMapTile tile,
208 final File pngfile, String pngurl,
211 boolean has_map = AltosSiteMapCache.has_map(pngfile, pngurl);
212 if ((load_mode & load_mode_uncached) == 0 && !has_map)
214 if ((load_mode & load_mode_cached) == 0 && has_map)
217 tile.set_status(AltosSiteMapCache.loading);
218 int status = AltosSiteMapCache.fetch_map(pngfile, pngurl);
219 if (status == AltosSiteMapCache.success) {
220 if (SwingUtilities.isEventDispatchThread())
221 tile.load_map(pngfile);
223 SwingUtilities.invokeLater(new Runnable() {
225 tile.load_map(pngfile);
230 tile.set_status(status);
231 System.out.printf("# Failed to fetch file %s (status %d)\n", pngfile, status);
232 System.out.printf(" wget -O '%s' '%s'\n", pngfile, pngurl);
233 System.out.printf(" sleep 1\n");
239 class AltosSiteMapPrefetch {
247 private AltosSiteMapPrefetch prefetchMap(int x, int y) {
248 AltosSiteMapPrefetch prefetch = new AltosSiteMapPrefetch();
249 LatLng map_latlng = latlng(
250 -centre.x + x*px_size + px_size/2,
251 -centre.y + y*px_size + px_size/2);
252 prefetch.pngfile = MapFile(map_latlng.lat, map_latlng.lng, zoom, maptype_hybrid);
253 prefetch.pngurl = MapURL(map_latlng.lat, map_latlng.lng, zoom, maptype_hybrid);
254 if (AltosSiteMapCache.has_map(prefetch.pngfile, prefetch.pngurl)) {
256 } else if (AltosSiteMapCache.fetch_map(prefetch.pngfile, prefetch.pngurl) == AltosSiteMapCache.success) {
259 prefetch.result = -1;
264 public static void prefetchMaps(double lat, double lng, int radius, int maptypes, int min_zoom, int max_zoom) {
265 AltosSiteMap asm = new AltosSiteMap(true);
267 for (int z = min_zoom; z <= max_zoom; z++) {
269 asm.set_radius(radius);
270 asm.centre = asm.getBaseLocation(lat, lng);
271 for (int t = maptype_hybrid; t <= maptype_terrain; t++) {
272 if ((maptypes & (1 << t)) !=0) {
274 for (int y = -radius; y <= radius; y++) {
275 for (int x = -radius; x <= radius; x++) {
276 AltosSiteMapPrefetch prefetch = asm.prefetchMap(x, y);
277 switch (prefetch.result) {
279 System.out.printf("Already have %s\n", prefetch.pngfile);
282 System.out.printf("Fetched map %s\n", prefetch.pngfile);
285 System.out.printf("# Failed to fetch file %s\n", prefetch.pngfile);
286 System.out.printf(" wget -O '%s' ''\n",
287 prefetch.pngfile, prefetch.pngurl);
297 public static void prefetchMaps(double lat, double lon) {
298 prefetchMaps(lat, lon, 2, 1 << maptype_hybrid, 0, 0);
301 public File init_map(Point offset, int load_mode) {
302 AltosSiteMapTile tile = mapTiles.get(offset);
303 Point2D.Double coord = tileCoordOffset(offset);
305 LatLng map_latlng = latlng(px_size/2-coord.x, px_size/2-coord.y);
307 File pngfile = MapFile(map_latlng.lat, map_latlng.lng, zoom, maptype);
308 String pngurl = MapURL(map_latlng.lat, map_latlng.lng, zoom, maptype);
309 load_map(tile, pngfile, pngurl, load_mode);
313 private void initAndFinishMapAsync (final AltosSiteMapTile tile, final Point offset) {
314 Thread thread = new Thread() {
316 init_map(offset, load_mode_cached|load_mode_uncached);
317 SwingUtilities.invokeLater( new Runnable() {
319 addTileAt(tile, offset);
328 boolean base_location_set = false;
330 public void clear_base_location() {
331 base_location_set = false;
333 points = new LinkedList<MapPoint>();
334 line_start = line_end = null;
335 for (AltosSiteMapTile tile : mapTiles.values()) {
337 tile.set_status(AltosSiteMapCache.loading);
341 public void setBaseLocation(double lat, double lng) {
344 base_location_set = true;
346 centre = getBaseLocation(lat, lng);
347 scrollRocketToVisible(pt(lat,lng));
350 private void initMaps(double lat, double lng) {
351 setBaseLocation(lat, lng);
353 for (AltosSiteMapTile tile : mapTiles.values()) {
355 tile.set_status(AltosSiteMapCache.loading);
357 Thread thread = new Thread() {
359 for (Point k : mapTiles.keySet())
360 init_map(k, load_mode_cached);
361 for (Point k : mapTiles.keySet())
362 init_map(k, load_mode_uncached);
368 private static File MapFile(double lat, double lng, int zoom, int maptype) {
369 char chlat = lat < 0 ? 'S' : 'N';
370 char chlng = lng < 0 ? 'W' : 'E';
371 if (lat < 0) lat = -lat;
372 if (lng < 0) lng = -lng;
373 String maptype_string = String.format("%s-", maptype_names[maptype]);
374 String format_string;
375 if (maptype == maptype_hybrid || maptype == maptype_satellite || maptype == maptype_terrain)
376 format_string = "jpg";
378 format_string = "png";
379 return new File(AltosUIPreferences.mapdir(),
380 String.format("map-%c%.6f,%c%.6f-%s%d.%s",
381 chlat, lat, chlng, lng, maptype_string, zoom, format_string));
384 private static String MapURL(double lat, double lng, int zoom, int maptype) {
385 String format_string;
386 if (maptype == maptype_hybrid || maptype == maptype_satellite || maptype == maptype_terrain)
387 format_string = "jpg";
389 format_string = "png32";
391 if (AltosUIVersion.has_google_maps_api_key())
392 return String.format("http://maps.google.com/maps/api/staticmap?center=%.6f,%.6f&zoom=%d&size=%dx%d&sensor=false&maptype=%s&format=%s&key=%s",
393 lat, lng, zoom, px_size, px_size, maptype_names[maptype], format_string, AltosUIVersion.google_maps_api_key);
395 return String.format("http://maps.google.com/maps/api/staticmap?center=%.6f,%.6f&zoom=%d&size=%dx%d&sensor=false&maptype=%s&format=%s",
396 lat, lng, zoom, px_size, px_size, maptype_names[maptype], format_string);
399 boolean initialised = false;
400 MapPoint last_point = null;
403 private void show(double lat, double lon) {
404 System.out.printf ("show %g %g\n", lat, lon);
406 // initMaps(lat, lon);
407 // scrollRocketToVisible(pt(lat, lon));
412 private void set_zoom_label() {
413 zoom_label.setText(String.format("Zoom %d", zoom - default_zoom));
416 public void set_zoom(int zoom) {
417 if (min_zoom <= zoom && zoom <= max_zoom) {
419 if (base_location_set) {
428 public int get_zoom() {
432 public void set_maptype(int type) {
434 maptype_combo.setSelectedIndex(type);
435 if (base_location_set)
440 private void draw(MapPoint last_point, MapPoint point) {
441 boolean force_ensure = false;
442 if (last_point == null) {
447 Point2D.Double pt = pt(point.lat, point.lon);
448 Point2D.Double last_pt = pt(last_point.lat, last_point.lon);
450 boolean in_any = false;
451 for (Point offset : mapTiles.keySet()) {
452 AltosSiteMapTile tile = mapTiles.get(offset);
453 Point2D.Double ref, lref;
454 ref = translatePoint(pt, tileCoordOffset(offset));
455 lref = translatePoint(last_pt, tileCoordOffset(offset));
456 tile.show(point.state, lref, ref);
457 if (0 <= ref.x && ref.x < px_size)
458 if (0 <= ref.y && ref.y < px_size)
462 Point offset = tileOffset(pt);
464 Point2D.Double ref, lref;
465 ref = translatePoint(pt, tileCoordOffset(offset));
466 lref = translatePoint(last_pt, tileCoordOffset(offset));
468 AltosSiteMapTile tile = createTile(offset);
469 tile.show(point.state, lref, ref);
470 initAndFinishMapAsync(tile, offset);
473 scrollRocketToVisible(pt);
475 if (force_ensure || offset != tileOffset(last_pt)) {
476 ensureTilesAround(offset);
480 private void redraw() {
481 MapPoint last_point = null;
483 for (MapPoint point : points) {
484 draw(last_point, point);
488 draw_circle(circle_lat, circle_lon);
489 if (line_start != null)
493 public void show(final AltosState state, final AltosListenerState listener_state) {
494 // if insufficient gps data, nothing to update
495 AltosGPS gps = state.gps;
500 if (!gps.locked && gps.nsat < 4)
504 if (state.pad_lat != AltosLib.MISSING && state.pad_lon != AltosLib.MISSING) {
505 initMaps(state.pad_lat, state.pad_lon);
507 } else if (gps.lat != AltosLib.MISSING && gps.lon != AltosLib.MISSING) {
508 initMaps(gps.lat, gps.lon);
515 MapPoint point = new MapPoint(gps.lat, gps.lon, state.state);
517 if (point.equals(last_point))
522 draw(last_point, point);
527 public void centre(Point2D.Double pt) {
528 Rectangle r = comp.getVisibleRect();
529 Point2D.Double copt = translatePoint(pt, tileCoordOffset(topleft));
530 int dx = (int)copt.x - r.width/2 - r.x;
531 int dy = (int)copt.y - r.height/2 - r.y;
536 comp.scrollRectToVisible(r);
539 public void centre(AltosState state) {
540 if (!state.gps.locked && state.gps.nsat < 4)
542 centre(pt(state.gps.lat, state.gps.lon));
545 private double circle_lat, circle_lon;
546 private boolean circle_set = false;
548 public void draw_circle(double lat, double lon) {
553 Point2D.Double pt = pt(lat, lon);
555 for (Point offset : mapTiles.keySet()) {
556 AltosSiteMapTile tile = mapTiles.get(offset);
557 Point2D.Double ref = translatePoint(pt, tileCoordOffset(offset));
562 private AltosSiteMapTile createTile(Point offset) {
563 AltosSiteMapTile tile = new AltosSiteMapTile(px_size);
564 tile.set_font(AltosUILib.value_font);
565 mapTiles.put(offset, tile);
569 private void ensureTilesAround(Point base_offset) {
570 for (int x = -radius; x <= radius; x++) {
571 for (int y = -radius; y <= radius; y++) {
572 Point offset = new Point(base_offset.x + x, base_offset.y + y);
573 if (mapTiles.containsKey(offset))
575 AltosSiteMapTile tile = createTile(offset);
576 initAndFinishMapAsync(tile, offset);
581 private void set_tiles() {
582 for (int x = -radius; x <= radius; x++) {
583 for (int y = -radius; y <= radius; y++) {
584 Point offset = new Point(x, y);
585 if (mapTiles.containsKey(offset))
587 AltosSiteMapTile t = createTile(offset);
588 addTileAt(t, offset);
591 for (Point offset : mapTiles.keySet()) {
592 if (offset.x < -radius || offset.x > radius ||
593 offset.y < -radius || offset.y > radius)
595 removeTileAt(offset);
600 public void set_radius(int radius) {
601 if (radius != this.radius) {
602 this.radius = radius;
607 private Point topleft = new Point(0,0);
608 private void scrollRocketToVisible(Point2D.Double pt) {
609 Rectangle r = comp.getVisibleRect();
610 Point2D.Double copt = translatePoint(pt, tileCoordOffset(topleft));
612 int dx = (int)copt.x - r.width/2 - r.x;
613 int dy = (int)copt.y - r.height/2 - r.y;
614 if (Math.abs(dx) > r.width/4 || Math.abs(dy) > r.height/4) {
617 comp.scrollRectToVisible(r);
621 private void addTileAt(AltosSiteMapTile tile, Point offset) {
622 if (Math.abs(offset.x) >= MAX_TILE_DELTA ||
623 Math.abs(offset.y) >= MAX_TILE_DELTA)
625 System.out.printf("Rocket too far away from pad (tile %d,%d)\n",
630 if (offset.x < topleft.x)
631 topleft.x = offset.x;
632 if (offset.y < topleft.y)
633 topleft.y = offset.y;
635 GridBagConstraints c = new GridBagConstraints();
636 c.anchor = GridBagConstraints.CENTER;
637 c.fill = GridBagConstraints.BOTH;
638 // put some space between the map tiles, debugging only
639 // c.insets = new Insets(5, 5, 5, 5);
641 c.gridx = offset.x + MAX_TILE_DELTA;
642 c.gridy = offset.y + MAX_TILE_DELTA;
643 layout.setConstraints(tile, c);
648 private AltosSiteMap(boolean knowWhatYouAreDoing) {
649 if (!knowWhatYouAreDoing) {
650 throw new RuntimeException("Arggh.");
654 private void removeTileAt(Point offset) {
655 AltosSiteMapTile tile = mapTiles.get(offset);
657 mapTiles.remove(offset);
660 topleft = new Point(MAX_TILE_DELTA, MAX_TILE_DELTA);
661 for (Point o : mapTiles.keySet()) {
671 private GridBagLayout layout = new GridBagLayout();
673 LatLng line_start, line_end;
675 private void set_line() {
676 if (line_start != null && line_end != null) {
677 Point2D.Double start = pt(line_start.lat, line_start.lng);
678 Point2D.Double end = pt(line_end.lat, line_end.lng);
679 AltosGreatCircle g = new AltosGreatCircle(line_start.lat, line_start.lng,
680 line_end.lat, line_end.lng);
682 for (Point offset : mapTiles.keySet()) {
683 AltosSiteMapTile tile = mapTiles.get(offset);
685 s = translatePoint(start, tileCoordOffset(offset));
686 e = translatePoint(end, tileCoordOffset(offset));
687 tile.set_line(new Line2D.Double(s.x, s.y, e.x, e.y), g.distance);
690 for (AltosSiteMapTile tile : mapTiles.values())
691 tile.set_line(null, 0);
695 static void debug_component(Component who, String where) {
697 Rectangle r = who.getBounds();
698 int x = r.x / px_size;
699 int y = r.y / px_size;
701 System.out.printf ("%3d, %3d: %s\n", x, y, where);
705 LatLng latlng(MouseEvent e) {
706 if (!base_location_set)
709 Rectangle zerozero = mapTiles.get(new Point(0, 0)).getBounds();
711 return latlng(-centre.x + e.getPoint().x - zerozero.x, -centre.y + e.getPoint().y - zerozero.y);
714 /* MouseMotionListener methods */
715 public void mouseDragged(MouseEvent e) {
716 if (!GrabNDrag.grab_n_drag(e)) {
717 LatLng loc = latlng(e);
723 public void mouseMoved(MouseEvent e) {
726 /* MouseListener methods */
727 public void mouseClicked(MouseEvent e) {
730 public void mouseEntered(MouseEvent e) {
733 public void mouseExited(MouseEvent e) {
736 public void mousePressed(MouseEvent e) {
737 if (!GrabNDrag.grab_n_drag(e)) {
738 LatLng loc = latlng(e);
745 public void mouseReleased(MouseEvent e) {
748 private void set_cache_size() {
749 Rectangle r = comp.getVisibleRect();
751 int width_tiles = (r.width + 2*px_size) / px_size;
752 int height_tiles = (r.height + 2*px_size) / px_size;
753 int tiles = width_tiles * height_tiles;
754 AltosSiteMapCache.set_cache_size(tiles);
757 /* HierarchyBoundsListener methods */
758 public void ancestorMoved(HierarchyEvent e) {
762 public void ancestorResized(HierarchyEvent e) {
766 JScrollPane pane = new JScrollPane();
768 JComboBox<String> maptype_combo;
770 public AltosSiteMap(int in_radius) {
773 comp = new JComponent() { };
775 comp.addMouseMotionListener(this);
776 comp.addMouseListener(this);
777 comp.addHierarchyBoundsListener(this);
779 GrabNDrag scroller = new GrabNDrag(comp);
781 comp.setLayout(layout);
785 pane.setViewportView(comp);
786 pane.setPreferredSize(new Dimension(500,500));
787 pane.setVisible(true);
788 pane.setEnabled(true);
790 GridBagLayout my_layout = new GridBagLayout();
792 setLayout(my_layout);
794 GridBagConstraints c = new GridBagConstraints();
795 c.anchor = GridBagConstraints.CENTER;
796 c.fill = GridBagConstraints.BOTH;
807 zoom_label = new JLabel("", JLabel.CENTER);
810 c = new GridBagConstraints();
811 c.anchor = GridBagConstraints.CENTER;
812 c.fill = GridBagConstraints.HORIZONTAL;
819 JButton zoom_reset = new JButton("0");
820 zoom_reset.addActionListener(new ActionListener() {
821 public void actionPerformed(ActionEvent e) {
822 set_zoom(default_zoom);
826 c = new GridBagConstraints();
827 c.anchor = GridBagConstraints.CENTER;
828 c.fill = GridBagConstraints.HORIZONTAL;
835 JButton zoom_in = new JButton("+");
836 zoom_in.addActionListener(new ActionListener() {
837 public void actionPerformed(ActionEvent e) {
838 set_zoom(get_zoom() + 1);
842 c = new GridBagConstraints();
843 c.anchor = GridBagConstraints.CENTER;
844 c.fill = GridBagConstraints.HORIZONTAL;
851 JButton zoom_out = new JButton("-");
852 zoom_out.addActionListener(new ActionListener() {
853 public void actionPerformed(ActionEvent e) {
854 set_zoom(get_zoom() - 1);
857 c = new GridBagConstraints();
858 c.anchor = GridBagConstraints.CENTER;
859 c.fill = GridBagConstraints.HORIZONTAL;
866 maptype_combo = new JComboBox<String>(maptype_labels);
868 maptype_combo.setEditable(false);
869 maptype_combo.setMaximumRowCount(maptype_combo.getItemCount());
870 maptype_combo.addItemListener(new ItemListener() {
871 public void itemStateChanged(ItemEvent e) {
872 maptype = maptype_combo.getSelectedIndex();
873 if (base_location_set)
879 c = new GridBagConstraints();
880 c.anchor = GridBagConstraints.CENTER;
881 c.fill = GridBagConstraints.HORIZONTAL;
886 add(maptype_combo, c);
889 public AltosSiteMap() {