Android地图和定位学习总结.docx
- 文档编号:9702472
- 上传时间:2023-02-05
- 格式:DOCX
- 页数:9
- 大小:19.72KB
Android地图和定位学习总结.docx
《Android地图和定位学习总结.docx》由会员分享,可在线阅读,更多相关《Android地图和定位学习总结.docx(9页珍藏版)》请在冰豆网上搜索。
Android地图和定位学习总结
-CAL-FENGHAI.-(YICAI)-CompanyOne1-CAL-本页仅作为文档封面,使用请直接删除
Android地图和定位学习总结(总12页)
Android地图和定位学习总结
首届Google暑期大学生博客分享大赛——2010Android篇
android.location包下有这么一些接口和类:
InterfacesGpsStatus.ListenerGpsStatus.NmeaListenerLocationListenerClassesAddressCriteriaGeocoderGpsSatelliteGpsStatusLocationLocationManagerLocationProvidercom.google.android.maps包下有这些类:
AllClassesGeoPointItemizedOverlayItemizedOverlay.OnFocusChangeListenerMapActivityMapControllerMapViewMapView.LayoutParamsMapView.ReticleDrawModeMyLocationOverlayOverlayOverlay.SnappableOverlayItemProjectionTrackballGestureDetector我们边看代码边熟悉这些类。
要获取当前位置坐标,就是从Location对象中获取latitude和longitude属性。
那Location对象是如何创建的?
LocationManagerlocMan=(LocationManager)getSystemService(Context.LOCATION_SERVICE);//LocationManager对象只能这么创建,不能用newLocationlocation=locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);if(location==null){
location=locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);}//注意要为应用程序添加使用权限
name="android.permission.ACCESS_FINE_LOCATION"/>所谓getLastKnownLocation自然是获取最新的地理位置信息,那LocationManager.GPS_PROVIDER和LocationManager.NETWORK_PROVIDER有什么区别呢? 俺也不是学通信的,对这个不了解,在网上看到有人想“在室外有GPS定位,在室内想用Wifi或基站定位”。 除了直接使用LocationManager提供的静态Provider(如GPS_PROVIDER和NETWORK_PROVIDER等)外,还可以使用我们自己创建的LocationProvider对象。 创建LocationProvider对象一般要先创建Criteria对象,来设置我们的LocationProvider要满足什么样的标准CriteriamyCri=newCriteria();myCri.setAccuracy(Criteria.ACCURACY_FINE);//精确度myCri.setAltitudeRequired(false);//海拔不需要myCri.setBearingRequired(false);//Bearing是“轴承”的意思,此处可理解为地轴线之类的东西,总之BearingInformation是一种地理位置信息的描述myCri.setCostAllowed(true);//允许产生现金消费myCri.setPowerRequirement(Criteria.POWER_LOW);//耗电StringmyProvider=locMan.getBestProvider(myCri,true); publicStringgetBestProvider(Criteriacriteria,booleanenabledOnly) Returnsthenameoftheproviderthatbestmeetsthegivencriteria.Onlyprovidersthatarepermittedtobeaccessedbythecallingactivitywillbereturned.Ifseveralprovidersmeetthecriteria,theonewiththebestaccuracyisreturned.Ifnoprovidermeetsthecriteria,thecriteriaareloosenedinthefollowingsequence: powerrequirementaccuracybearingspeedaltitudeNotethattherequirementonmonetarycostisnotremovedinthisprocess.ParameterscriteriathecriteriathatneedtobematchedenabledOnlyiftruethenonlyaproviderthatiscurrentlyenabledisreturnedReturnsnameoftheproviderthatbestmatchestherequirementsonly翻译为“最适合的"Locationlocation=locMan.getLastKnownLoation(myProvider);doublelatitude=location.getLatitude();//获取纬度doublelongitude=location.getLongitude();//获取经度 我想知道当前位置描述(比如“武汉华中科技大学”而不是一个经纬值)呢? 这就要使用GeoCoder创建一个Address对象了。 Geocodergc=newGeocoder(context,Locale.CHINA);//Locale是java.util中的一个类List
List
getFromLocation(doublelatitude,doublelongitude,intmaxResults)ReturnsanarrayofAddressesthatareknowntodescribetheareaimmediatelysurroundingthegivenlatitudeandlongitude.(返回给定经纬值附近的一个Address)既然是“附近”那实际编码时我们没必要把经纬值给的那么精确,而取一个近似的整数,像这样:
/*自经纬度取得地址,可能有多行地址*/
List
listAddress=gc.getFromLocation((int)latitude,(int)longitude,1);StringBuildersb=newStringBuilder();
/*判断是不否为多行*/if(listAddress.size()>0){Addressaddress=listAddress.get(0);
for(inti=0;i
sb.append(address.getAddressLine(i)).append("\n");
}
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName()).append("\n");
}
publicintgetMaxAddressLineIndex()
Since:
APILevel1
Returnsthelargestindexcurrentlyinusetospecifyanaddressline.Ifnoaddresslinesarespecified,-1isreturned.
publicStringgetAddressLine(intindex)
Since:
APILevel1
Returnsalineoftheaddressnumberedbythegivenindex(startingat0),ornullifnosuchlineispresent.
StringgetCountryName()
Returnsthelocalizedcountrynameoftheaddress,forexample"Iceland",ornullifitisunknown.
StringgetLocality()
Returnsthelocalityoftheaddress,forexample"MountainView",ornullifitisunknown.
反过来我们可以输入地址信息获取经纬值
GeocodermygeoCoder=newGeocoder(myClass.this,Locale.getDefault());
List
lstAddress=mygeoCoder.getFromLocationName(strAddress,1); //strAddress是输入的地址信息if(!
lstAddress.isEmpty()){
Addressaddress=lstAddress.get(0);
doublelatitude=address.getLatitude()*1E6;
doublelongitude=adress.getLongitude()*1E6;
GeoPointgeopoint=newGeoPoint((int)latitude,(int)longitude);
}
Aclassforhandlinggeocodingandreversegeocoding.Geocodingistheprocessoftransformingastreetaddressorotherdescriptionofalocationintoa(latitude,longitude)coordinate.
PublicConstructors
Geocoder(Contextcontext,Localelocale)ConstructsaGeocoderwhoseresponseswillbelocalizedforthegivenLocale.
Geocoder(Contextcontext)ConstructsaGeocoderwhoseresponseswillbelocalizedforthedefaultsystemLocale.
publicList
getFromLocationName(StringlocationName,intmaxResults)Since:
APILevel1
ReturnsanarrayofAddressesthatareknowntodescribethenamedlocation,whichmaybeaplacename
suchas"Dalvik,Iceland",anaddresssuchas"1600AmphitheatreParkway,MountainView,CA",anairport
codesuchas"SFO",etc..Thereturnedaddresseswillbelocalizedforthelocaleprovidedtothisclass's
constructor.
Thequerywillblockandreturnedvalueswillbeobtainedbymeansofanetworklookup.Theresultsareabest
guessandarenotguaranteedtobemeaningfulorcorrect.Itmaybeusefultocallthismethodfromathread
separatefromyourprimaryUIthread.
Parameters
locationName
auser-supplieddescriptionofalocation
maxResults
maxnumberofresultstoreturn.Smallernumbers(1to5)arerecommended
Returns
alistofAddressobjects.Returnsnulloremptylistifnomatcheswerefoundorthereisnobackend
serviceavailable.
Throws
IllegalArgumentException
iflocationNameisnull
IOException
ifthenetworkisunavailableoranyotherI/Oproblemoccurs
说了半天还只是个定位,地图还没出来。
下面要用到com.google.android.maps包了
下面的代码我们让地图移到指定点
GeoPointp=newGeoPoint((int)(latitude*1E6),(int)(longitude*1E6));
MapViewmapview=(MapView)findViewById(R.id.mv);
MapControllermapContr=mapview.getController();
mapview.displayZoomControls(true);//显示地图缩放的按钮
mapContr.animateTo(p);//带动画移到p点
mapContr.setZoom(7);
setZoom
publicintsetZoom(intzoomLevel)
Setsthezoomlevelofthemap.Thevaluewillbeclampedtobebetween1and21inclusive,though
notallareashavetilesathigherzoomlevels.Thisjustsetsthelevelofthezoomdirectly;fora
step-by-stepzoomwithfancyinterstitialanimations,usezoomIn()orzoomOut().
Parameters:
zoomLevel-AtzoomLevel1,theequatoroftheearthis256pixelslong.Eachsuccessivezoom
levelismagnifiedbyafactorof2.
Returns:
thenewzoomlevel,between1and21inclusive.
在地图上指定一点给出经纬值
@Override
publicbooleanonTouchEvent(MotionEventev){
intactionType=ev.getAction();
switch(actionType){
caseMotionEvent.ACTION_UP:
Projectionprojection=mapview.getProjection();
GeoPointloc=projection.fromPixels((int)arg0.getX(),(int)arg0.getY());
StringlngStr=Double.toString(loc.getLongitudeE6()/1E6);
StringlatStr=Double.toString(loc.getLatitudeE6()/1E6);
}
returnfalse;
}
publicinterfaceProjection
AProjectionservestotranslatebetweenthecoordinatesystemofx/yon-screenpixelcoordinatesandthat
oflatitude/longitudepointsonthesurfaceoftheearth.YouobtainaProjectionfromMapView.getProjection().
如果需要我们还可以把经纬值转换成手机的屏幕坐标值PointscreenCoords=newPoint();//android.graphics.Point;GeoPointgeopoint=newGeoPoint((int)(latitude*1E6),(int)(longitude*1E6));mapview.getProjection().toPixels(geopoint,screenCoords);intx=screenCoords.x;inty=screenCoords.y;放大缩小地图主要就是用setZoom(intZoomLevel)函数,让ZoomLevel不停往上涨(或往下降)就可以了下面给出一个com.google.android.maps.Overlay的使用例子importcom.google.android.maps.GeoPoint;importcom.google.android.maps.MapActivity;importcom.google.android.maps.MapController;importcom.google.android.maps.MapView;importcom.google.android.maps.Overlay;importandroid.graphics.Bitmap;importandroid.graphics.BitmapFactory;importandroid.graphics.Canvas;importandroid.graphics.Point;importandroid.os.Bundle;importandroid.view.View;
publicclassMapsActivityextendsMapActivity{MapViewmapView;MapControllermc;GeoPointp;classMapOverlayextendscom.google.android.maps.Overlay{@Overridepublicbooleandraw(Canvascanvas,MapViewmapView,booleanshadow,longwhen){super.draw(canvas,mapView,shadow);//---translatetheGeoPointtoscreenpixels---PointscreenPts=newPoint();mapView.getProjection().toPixels(p,screenPts);//---addthemarker---Bitmapbmp=BitmapFactory.decodeResource(getResources(),R.drawable.pushpin);canvas.drawBitmap(bmp,screenPts.x,screenPts.y-50,null);returntrue;}}/**Calledwhentheactivityisfirstcreated.*/@OverridepublicvoidonCreate(BundlesavedInstanceState){//...}@OverrideprotectedbooleanisRouteDisplayed(){//TODOAuto-generatedmethodstubreturnfalse;}}publicvoiddraw(android.graphics.Canvascanvas,
MapViewmapView,
booleanshadow)
Drawtheoverlayoverthemap.Thiswillbecalledonallactiveoverlayswithshadow=true,tolaydown
theshadowlayer,andthenagainonalloverlayswithshadow=false.Bydefault,drawsnothing.
Parameters:
canvas-TheCanvasuponwhichtodraw.Notethatthismayalreadyhaveatransformationapplied,sobesure
toleaveitthewayyoufoundit.
mapView-theMapViewthatrequestedthedraw.UseMapView.getProjection()toconvertbetween
on-screenpixelsandlatitude/longitudepairs.
shadow-Iftrue,drawtheshadowlayer.Iffalse,drawtheoverlaycontents.publicbooleand
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Android 地图 定位 学习 总结
![提示](https://static.bdocx.com/images/bang_tan.gif)