53

hard-coding the setZoom() within onCreate() feels very antiquated and I'd like to enhance the user experience by initially having the MapView set the zoom until all GeoPoints / OverlayItems are visible on the map.

How can this be done auto-magically?

Reno
  • 33,594
  • 11
  • 89
  • 102
Someone Somewhere
  • 23,475
  • 11
  • 118
  • 166

2 Answers2

128

Kinda like this

int minLat = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int minLon = Integer.MAX_VALUE;
int maxLon = Integer.MIN_VALUE;

for (GeoPoint item : items) 
{ 

      int lat = item.getLatitudeE6();
      int lon = item.getLongitudeE6();

      maxLat = Math.max(lat, maxLat);
      minLat = Math.min(lat, minLat);
      maxLon = Math.max(lon, maxLon);
      minLon = Math.min(lon, minLon);
 }

mapController.zoomToSpan(Math.abs(maxLat - minLat), Math.abs(maxLon - minLon));
mapController.animateTo(new GeoPoint( (maxLat + minLat)/2, 
(maxLon + minLon)/2 )); 

edit: Ryan gave a nice suggestion : to put a padding so that some of the point don't lie on the edges (thanks Ryan!)

double fitFactor = 1.5;
mapController.zoomToSpan((int) (Math.abs(maxLat - minLat) * fitFactor), (int)(Math.abs(maxLon - minLon) * fitFactor));
Reno
  • 33,594
  • 11
  • 89
  • 102
  • 10
    I use this for two geopoints, my location and a point of interest, and I noticed sometimes the overlays are very near the edge of the screen. To fix this I added a `double fitFactor = 1.5` to `mapController.zoomToSpan((int) Math.abs(maxLat - minLat) * fitFactor), (int)(Math.abs(maxLon - minLon) * fitFactor));` which adds a nice padding. – Ryan R Jan 05 '12 at 06:36
  • 2
    Great answer. There's a ( missing in the last line of the edited version, should be: `mapController.zoomToSpan((int)(Math.abs(maxLat - minLat) * fitFactor), (int)(Math.abs(maxLon - minLon) * fitFactor));` – Mick Byrne Feb 21 '12 at 02:59
  • It can also contain a check ie **items list should not be empty** otherwise the map is zoomed to level 1. For me, it is working for most of the cases. – Raman Ghai May 08 '13 at 22:13
  • Thanks Reno for the answer and Thanks Ryan for the improvement point. – Paresh Mayani Jun 26 '13 at 11:48
2

There's no magical way to achieve this. I suggest to iterate through all your overlayitems to obtain the center and span of all these items. Then set the center and span accordingly for the map

pankajagarwal
  • 13,462
  • 14
  • 54
  • 65