Android地图和定位学习总结文档格式.docx
《Android地图和定位学习总结文档格式.docx》由会员分享,可在线阅读,更多相关《Android地图和定位学习总结文档格式.docx(9页珍藏版)》请在冰豆网上搜索。
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<
Address>
listAddress=gc.getFromLocation(latitude,longitude,1);
List<
getFromLocation(doublelatitude,doublelongitude,intmaxResults)ReturnsanarrayofAddressesthatareknowntodescribetheareaimmediatelysurroundingthegivenlatitudeandlongitude.(返回给定经纬值附近的一个Address)
既然是“附近”那实际编码时我们没必要把经纬值给的那么精确,而取一个近似的整数,像这样:
/*自经纬度取得地址,可能有多行地址*/
listAddress=gc.getFromLocation((int)latitude,(int)longitude,1);
StringBuildersb=newStringBuilder();
/*判断是不否为多行*/if(listAddress.size()>
0){Addressaddress=listAddress.get(0);
for(inti=0;
i<
address.getMaxAddressLineIndex();
i++){
sb.append(address.getAddressLine(i)).append("
\n"
);
}
sb.append(address.getLocality()).append("
sb.append(address.getPostalCode()).append("
sb.append(address.getCountryName()).append("
}
publicintgetMaxAddressLineIndex()
Since:
APILevel1
Returnsthelargestindexcurrentlyinusetospecifyanaddressline.Ifnoaddresslinesarespecified,-1isreturned.
publicStringgetAddressLine(intindex)
Returnsalineoftheaddressnumberedbythegivenindex(startingat0),ornullifnosuchlineispresent.
StringgetCountryName()
Returnsthelocalizedcountrynameoftheaddress,forexample"
Iceland"
ornullifitisunknown.
StringgetLocality()
Returnsthelocalityoftheaddress,forexample"
MountainView"
反过来我们可以输入地址信息获取经纬值
GeocodermygeoCoder=newGeocoder(myClass.this,Locale.getDefault());
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)
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.
canvas-TheCanvasuponwhichtodraw.Notethatthismayalreadyhaveatransformationapplied,sobesure
toleaveitthewayyoufoundit.
mapView-theMapViewthatrequestedthedraw.UseMapView.getProjection()toconvertbetween
on-screenpixelsandlatitude/longitudepairs.
shadow-Iftrue,drawtheshadowlayer.Iffalse,drawtheoverlaycontents.publicbooleand