Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
200 views

Setting Max Zoom Level in Google Maps Android API v2 - Stack Overflow

Stack Overflow is a question and answer site for professional and enthusiast programmers. The question asks how to set a maximum zoom level in Google Maps Android API v2 to prevent zooming past a certain level. Several answers are provided, including listening for camera change events and adjusting the zoom, animating to a specific zoom level first before getting bounds, and disabling the default zoom controls to add custom buttons with zoom limits.

Uploaded by

Omar Muñiz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
200 views

Setting Max Zoom Level in Google Maps Android API v2 - Stack Overflow

Stack Overflow is a question and answer site for professional and enthusiast programmers. The question asks how to set a maximum zoom level in Google Maps Android API v2 to prevent zooming past a certain level. Several answers are provided, including listening for camera change events and adjusting the zoom, animating to a specific zoom level first before getting bounds, and disabling the default zoom controls to add custom buttons with zoom limits.

Uploaded by

Omar Muñiz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

signup

StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free,no
registrationrequired.

login

tour

Settingmaxzoomlevelingooglemapsandroidapiv2StackOverflow

23/3/2015

help

stackoverflowcareers

Takethe2minutetour

Settingmaxzoomlevelingooglemapsandroidapiv2

I'mcurrentlyworkingondevelopingappsbyusingGooglemapsandroidAPIv2.Mycodeisasfollows.Supposemaphasseveralmarkers
andzoomuptoshowallmarkersindisplay.
LatLngBuilder.Builderbuilder=LatLngBounds.builder();
for(Markerm:markers){
builder.include(m.getPosition());
}
LatLngBoundsbounds=builder.build();
map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds,10);

ThiscodeisworkingfinebutIwanttostopanimatingwhenthezoomlevelreachedto17.0fItseemsmapAPIdoesnothavesuchmethod
tocontrolzoomlevel.Doesanybodyknowanyideatosolvethisproblem?
android maps zoom

editedApr27'14at0:09

askedMar29'13at9:44

joao2fast4u

user2223820

3,880

27

66

10Answers

IhavenotfoundanydirectsolutionintheGoogleMapsAPI.Apotentialsolutiontothisproblem
consistsinlisteningagainsttheOnCameraChangeevent:Wheneverthiseventtriggersandthe
zoomlevelisabovethemaximumzoomlevel,itispossibletocallanimateCamera().The
resultingcodewouldbethefollowing:
@Override
publicvoidonCameraChange(CameraPositionposition){
floatmaxZoom=17.0f;
if(position.zoom>maxZoom)
map_.animateCamera(CameraUpdateFactory.zoomTo(maxZoom));
}

answeredJun18'13at17:39
Tisys
439

12

thanksforyourcommnet.i'vetriedthisbutitseemsonCameraChangecalledafteranimating,sozoomlevel
canbegraterthan17.0sometimes. user2223820 Jun22'13at5:54

HereisthecorrespondingJavacodeforArvis'solutionwhichworkedwellforme:
privateLatLngBoundsadjustBoundsForMaxZoomLevel(LatLngBoundsbounds){
LatLngsw=bounds.southwest;
LatLngne=bounds.northeast;
doubledeltaLat=Math.abs(sw.latitudene.latitude);
doubledeltaLon=Math.abs(sw.longitudene.longitude);
finaldoublezoomN=0.005;//minimumzoomcoefficient
if(deltaLat<zoomN){
sw=newLatLng(sw.latitude(zoomNdeltaLat/2),sw.longitude);
ne=newLatLng(ne.latitude+(zoomNdeltaLat/2),ne.longitude);
bounds=newLatLngBounds(sw,ne);
}
elseif(deltaLon<zoomN){
sw=newLatLng(sw.latitude,sw.longitude(zoomNdeltaLon/2));
ne=newLatLng(ne.latitude,ne.longitude+(zoomNdeltaLon/2));
bounds=newLatLngBounds(sw,ne);
}

http://stackoverflow.com/questions/15700808/settingmaxzoomlevelingooglemapsandroidapiv2

1/5

23/3/2015

Settingmaxzoomlevelingooglemapsandroidapiv2StackOverflow

returnbounds;
}

answeredOct13'13at9:47
kasimir
573

10

Thxalot.Ihaveaquestionaboutzoomcoefficient.Howtranslateandroidzoomlevel(17inthisthread)to
zoomN ? aat Oct17'13at8:48
SorryIdidn'tneedtodoityet...soIdon'tknowyet:)kasimirOct17'13at20:11
Hello@kasimir,wherehaveyouputthiscodetocontrolthemaxzoomlevel?Isitjustaconfigurationwhen
theGoogleMapobjectiscreated?IgnacioRubioDec17'14at8:13
1 @IgnacioRubioSorrydon'tknowhowtoformatcodehere,buttrythis:bounds=
adjustBoundsForMaxZoomLevel(bounds)intpadding=10//offsetfromedgesofthemapinpixels
CameraUpdatecu=CameraUpdateFactory.newLatLngBounds(bounds,padding)
mGoogleMap.animateCamera(cu)kasimirDec17'14at9:53

BeforeanimateCamerayoucancheckifSWandNEpointsofboundsarenottoocloseandif
necessaryadjustbounds:
...
LatLngBoundsbounds=builder.Build();
varsw=bounds.Southwest;
varne=bounds.Northeast;
vardeltaLat=Math.Abs(sw.Latitudene.Latitude);
vardeltaLon=Math.Abs(sw.Longitudene.Longitude);
constdoublezoomN=0.005;//setwhateverzoomcoefficientyouneed!!!
if(deltaLat<zoomN){
sw.Latitude=sw.Latitude(zoomNdeltaLat/2);
ne.Latitude=ne.Latitude+(zoomNdeltaLat/2);
bounds=newLatLngBounds(sw,ne);
}
elseif(deltaLon<zoomN){
sw.Longitude=sw.Longitude(zoomNdeltaLon/2);
ne.Longitude=ne.Longitude+(zoomNdeltaLon/2);
bounds=newLatLngBounds(sw,ne);
}
map.animateCamera(CameraUpdateFactory.NewLatLngBounds(bounds,10);

ps.Myexampleisinc#codebutyoucaneaslyadjustitforjava
editedOct14'13at10:48

answeredAug13'13at10:44
Arvis
2,502

16

27

Thanks,IaddedthecorrespondingJavacodeinananswerbelow.kasimirOct13'13at9:43

Imnotsureifthiswillworkbutcanyoutrythis
map.animateCamera(CameraUpdateFactory.zoomTo(10),2000,null);

Hopeithelps
answeredJun18'13at12:37
BenilMathew
898

11

unfortunately,thisdidn'tworkwell.thanksforyourhelpthough. user2223820 Jun22'13at5:55

ThisisfromtheAPIreferenceforthe include(position) you'reusing:


"Includesthispointforbuildingofthebounds.Theboundswillbeextendedinaminimumwayto
includethispoint.Moreprecisely,itwillconsiderextendingtheboundsbothintheeastwardand
westwarddirections(oneofwhichmaywraparoundtheworld)andchoosethesmallerofthe
two.InthecasethatbothdirectionsresultinaLatLngBoundsofthesamesize,thiswillextendit
intheeastwarddirection."
Themapwillzoomoutuntilitcanshowallofthemarkersyou'readdinginyourforloop.
Ifyouwanttoonlyzoomoutto17andstillshowmarkers,animatetozoomlevel17first,thenget
theboundsforit,andthenaddyourmarkers.

http://stackoverflow.com/questions/15700808/settingmaxzoomlevelingooglemapsandroidapiv2

2/5

23/3/2015

Settingmaxzoomlevelingooglemapsandroidapiv2StackOverflow

@Override
publicvoidonCameraChange(CameraPositioncamPos){
if(camPos.zoom<17&&mCurrentLoc!=null){
//setzoom17anddisablezoomgesturessomapcan'tbezoomedout
//alltheway
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(position,17));
mMap.getUiSettings().setZoomGesturesEnabled(false);
}
if(camPos.zoom>=17){
mMap.getUiSettings().setZoomGesturesEnabled(true);
}
LatLngBoundsvisibleBounds=mMap.getProjection().getVisibleRegion().latLngBounds;
//addthemarkers

answeredJul31'13at10:44
vdisawar
66

@kasimir'sapproachsetsaminimumnumberofdegreesineitherthelatitudeorlongitude,and
feltalittlehardtoread.SoItweakedittojustsetaminimumonthelatitude,whichIfeltlikewasa
bitmorereadable:
privateLatLngBoundsadjustBoundsForMinimumLatitudeDegrees(LatLngBoundsbounds,double
minLatitudeDegrees){
LatLngsw=bounds.southwest;
LatLngne=bounds.northeast;
doublevisibleLatitudeDegrees=Math.abs(sw.latitudene.latitude);
if(visibleLatitudeDegrees<minLatitudeDegrees){
LatLngcenter=bounds.getCenter();
sw=newLatLng(center.latitude(minLatitudeDegrees/2),sw.longitude);
ne=newLatLng(center.latitude+(minLatitudeDegrees/2),ne.longitude);
bounds=newLatLngBounds(sw,ne);
}
returnbounds;
}

editedOct20'14at23:20

answeredOct20'14at23:01
ChristopherPickslay
10.6k

45

69

WhatIendedupdoingiscreatingmyownbuttonsanddisablingthedefaultonessoIwouldhave
fullcontrol.
Somethinglikethisinthelayouttoplacethebuttons:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="bottom"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true">
<Button
android:id="@+id/bzoomin"
android:layout_width="55dp"
android:layout_height="55dp"
android:gravity="center"
android:textSize="28sp"
android:text="+"/>
<Button
android:id="@+id/bzoomout"
android:layout_width="55dp"
android:layout_height="55dp"
android:gravity="center"
android:textSize="23sp"
android:text=""/>
</LinearLayout>

Thenthisinthecodetodisablethedefaultbuttonsandsetupournewones:
map.getUiSettings().setZoomControlsEnabled(false);
//setupzoomcontrolbuttons
Buttonzoomout=(Button)findViewById(R.id.bzoomout);
zoomout.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
if(map.getCameraPosition().zoom>=8.0f){
//Zoomlikenormal
map.animateCamera(CameraUpdateFactory.zoomOut());
}else{
//Dowhateveryouwantifuserwenttoofar

http://stackoverflow.com/questions/15700808/settingmaxzoomlevelingooglemapsandroidapiv2

3/5

23/3/2015

Settingmaxzoomlevelingooglemapsandroidapiv2StackOverflow

Messages.toast_short(MapsActivity.this,"Maximumzoomoutlevelreached");
}
}
});
Buttonzoomin=(Button)findViewById(R.id.bzoomin);
zoomin.setOnClickListener(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
if(map.getCameraPosition().zoom<=14.0f){
//Zoomlikenormal
map.animateCamera(CameraUpdateFactory.zoomIn());
}else{
//Dowhateveryouwantifuserwenttoofar
Messages.toast_short(MapsActivity.this,"Maximumzoominlevelreached");
}
}
});

answeredNov19'14at7:06
WilliamW
534

11

23

Hi@WilliamW.Thissolvethebuttons,butwhataboutthepinch&zoomwiththefingersonthescreen?
IgnacioRubioDec16'14at16:42
@IgnacioRubioYoucandisableallgestureswith map.getUiSettings().setAllGesturesEnabled(false);
orjustpinchtozoomwith map.getUiSettings().setZoomGesturesEnabled(false); WilliamWDec16
'14at17:10
Butamapwithzoomgestureddisabledwouldhaveabaduserexperience.Imean,I'mlookingforsetting
thezoomtoamaxlevelbutIwouldlikethattheusercoulduseboth,buttonsandfingergestures.Ihave
foundthatitexistsintheOSMAPI:code.google.com/p/osmdroid/issues/detail?id=418ButI'musing
googlemaps,soIneedtofindasolutionforthis IgnacioRubioDec16'14at17:17
1 @IgnacioRubioVerytruethatinmostcasesdisablingpinchtozoomisbadUX.It'swhatIendedupdoing
inmycasethough.TheonlythingItriedwastheanswerfromTisys.Howeverwhileittechnicallyworks,it
doesn'tworkverywellandismostlyfrustratingfortheuser.Ihaven'tlookedintosomeoftheother
suggestionsonthispage.WilliamWDec16'14at17:24
IhaveusedtheTisyssolution.Itworksfineforme.It'struethatforaninstantoftime,theusercouldzoom
morethanthemaxzoomlevel(becauseonCameraChangeiscalledafteranimating).Butthezoomis
quicklyrestablishedtomax.(ItwouldbebetteriftheAPIhadthe"setMaxZoomLevel"methodastheOSM
butformeit'sperfect)IgnacioRubioDec17'14at8:34

Youcangetthemaxzoomlevelbycallingit getMaxZoomLevel() andthensetthatvalue:


mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(fromPosition,
getMaxZoomLevel()));

editedJun18'13at13:10

answeredJun18'13at12:46

kgdesouz
788

AshishKumarAgrawal
6

16

44

iwilltrythis.thankyou. user2223820 Jun22'13at5:56


ifthishelpyouthenpleaseaccepttheanswer.allthebestAshishKumarAgrawalJun22'13at6:44
1 Hi.itriedthis.newLatLngZoomseemsnotabletouseLatLngBounds.iwanttozoomallmarkersincluding
ANDzoomlevel<=17.0. user2223820 Jun22'13at7:36

if(map.getZoom()>17)
map.setZoom(17);

Itworkedforme.Ithastobeaddedrightafterthemarkerloop.
answeredAug21'14at11:00
AbhishekChakraborty
1

1 Thereareno getZoom or setZoom methodsontheandroidGoogleMapAPI.ChristopherPickslay Oct


20'14at22:52

ThemaphasapropertycalledmaxZoom.Simplysetthistoyourvaluewhenyoucreate
yourmap
answeredMar29'13at9:50
abd
48

http://stackoverflow.com/questions/15700808/settingmaxzoomlevelingooglemapsandroidapiv2

4/5

23/3/2015

Settingmaxzoomlevelingooglemapsandroidapiv2StackOverflow

Thankyouforyourcomment.IsitalsoavailableonAPIv2?Idon'tseeanyitemlikemaxZoomin
GoogleMapobject. user2223820 Mar31'13at23:17
Ialsocan'tseesuchproperty.IsitonAndroidorjs?ronmeApr21'13at20:40
Thisisreadonlyproperty(incaseofMonodroid)Arvis May14'13at14:18

http://stackoverflow.com/questions/15700808/settingmaxzoomlevelingooglemapsandroidapiv2

5/5

You might also like