android 基于百度地图api开发定位以及获取详细地址
16lz
2022-03-24
一:百度地图开发必须要到百度开发平台android开发api下载相应的库,已经申请百度地图开发key,在这个博客里面有详细的说明和演示,(如果不懂得请看此文章)http://104zz.iteye.com/blog/1680781
二:新建项目baidumaplocation.设计main.xml文件这里注意的是MapView控件必须使用来自百度库封装好的com.baidu.mapapi.MapView。设计代码如下:
Xml代码- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical">
- <FrameLayout
- android:id="@+id/map_layout"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical">
- <!--百度MapView控件-->
- <com.baidu.mapapi.MapView
- android:id="@+id/map_view"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:apiKey="0Mg_koWoyZUiYLfZxmPfp4LKInB5LqTnagYueaw"
- android:clickable="true"
- android:enabled="true"/>
- <LinearLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center"
- android:orientation="vertical"
- android:paddingBottom="105dip">
- <!--地址信息显示TextView-->
- <TextView
- android:id="@+id/map_bubbleText"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:background="@drawable/location_tips"
- android:gravity="left|center"
- android:maxEms="12"
- android:paddingLeft="12dip"
- android:paddingRight="10dip"
- android:text="@string/load_tips"
- android:textColor="#cfcfcf"
- android:textSize="14sp"/>
- </LinearLayout>
- <LinearLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center"
- android:orientation="vertical">
- <!--位置指标显示ImageView-->
- <ImageView
- android:id="@+id/point_image"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center"
- android:layout_marginBottom="30dip"
- android:src="@drawable/point_start"/>
- </LinearLayout>
- </FrameLayout>
- </LinearLayout>
三:创建覆盖整个地图捕捉触控事件的MyMapOverlay继承Overlay
Java代码- importandroid.view.MotionEvent;
- importcom.baidu.mapapi.GeoPoint;
- importcom.baidu.mapapi.MapView;
- importcom.baidu.mapapi.Overlay;
- //覆盖整个地图捕捉触控事件的OverLay
- publicabstractclassMyMapOverlayextendsOverlay{
- privateintpoint_X;
- privateintpoint_Y;
- privateGeoPointnewPoint;
- publicMyMapOverlay(intx,inty){
- point_X=x;
- point_Y=y;
- }
- booleanflagMove=false;
- //这里实现根据地图移动时重新获取屏幕中心点的经纬度坐标
- @Override
- publicbooleanonTouchEvent(MotionEventevent,MapViewmapView){
- System.out.println("X->"+event.getX()+":"+point_X);
- System.out.println("Y->"+event.getY()+":"+point_Y);
- if(event.getAction()==MotionEvent.ACTION_DOWN){
- changePoint(newPoint,1);
- }elseif(event.getAction()==MotionEvent.ACTION_UP){
- newPoint=mapView.getProjection().fromPixels(point_X,point_Y);
- changePoint(newPoint,2);
- }
- returnfalse;
- }
- publicabstractvoidchangePoint(GeoPointnewPoint,inttype);
- }
四:LocationActivity类继承百度库的MapActivity以及实现LocationListener接口,代码如下:
package com.location.activity;
Java代码- importjava.io.IOException;
- importjava.util.List;
- importjava.util.Locale;
- importandroid.content.Intent;
- importandroid.location.Address;
- importandroid.location.Geocoder;
- importandroid.location.Location;
- importandroid.os.Bundle;
- importandroid.os.Handler;
- importandroid.os.Message;
- importandroid.view.View;
- importandroid.view.Window;
- importandroid.widget.TextView;
- importcom.android.map.MyMapOverlay;
- importcom.baidu.mapapi.BMapManager;
- importcom.baidu.mapapi.GeoPoint;
- importcom.baidu.mapapi.LocationListener;
- importcom.baidu.mapapi.MKAddrInfo;
- importcom.baidu.mapapi.MKBusLineResult;
- importcom.baidu.mapapi.MKDrivingRouteResult;
- importcom.baidu.mapapi.MKLocationManager;
- importcom.baidu.mapapi.MKPoiResult;
- importcom.baidu.mapapi.MKSearch;
- importcom.baidu.mapapi.MKSearchListener;
- importcom.baidu.mapapi.MKSuggestionResult;
- importcom.baidu.mapapi.MKTransitRouteResult;
- importcom.baidu.mapapi.MKWalkingRouteResult;
- importcom.baidu.mapapi.MapActivity;
- importcom.baidu.mapapi.MapController;
- importcom.baidu.mapapi.MapView;
- importcom.baidu.mapapi.Overlay;
- publicclassLocationActivityextendsMapActivityimplementsLocationListener{
- privateMapViewmapView;
- privateMapControllermMapCtrl;
- privateList<Overlay>mapOverlays;
- publicGeoPointlocPoint;
- privateMyMapOverlaymOverlay;
- privateTextViewdesText;
- privateStringlost_tips;
- privateintpoint_X;
- privateintpoint_Y;
- publicfinalintMSG_VIEW_LONGPRESS=10001;
- publicfinalintMSG_VIEW_ADDRESSNAME=10002;
- publicfinalintMSG_GONE_ADDRESSNAME=10003;
- privateIntentmIntent;
- privateintmLatitude;
- privateintmLongitude;
- privateStringname;
- privateBMapManagermapManager;
- privateMKLocationManagermLocationManager=null;
- privatebooleanisLoadAdrr=true;
- privateMKSearchmMKSearch;
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- requestWindowFeature(Window.FEATURE_NO_TITLE);
- setContentView(R.layout.main);
- initMap();
- mIntent=getIntent();
- mLatitude=mIntent.getIntExtra("latitude",0);
- mLongitude=mIntent.getIntExtra("longitude",0);
- name=mIntent.getStringExtra("name");
- mapView=(MapView)findViewById(R.id.map_view);
- desText=(TextView)this.findViewById(R.id.map_bubbleText);
- lost_tips=getResources().getString(R.string.load_tips);
- if(mLatitude!=0&&mLongitude!=0){
- locPoint=newGeoPoint((int)(mLatitude*1E6),
- (int)(mLongitude*1E6));
- desText.setText(name);
- }
- mapView.setBuiltInZoomControls(true);
- mapView.setClickable(true);
- mMapCtrl=mapView.getController();
- point_X=this.getWindowManager().getDefaultDisplay().getWidth()/2;
- point_Y=this.getWindowManager().getDefaultDisplay().getHeight()/2;
- mOverlay=newMyMapOverlay(point_X,point_Y){
- @Override
- publicvoidchangePoint(GeoPointnewPoint,inttype){
- if(type==1){
- mHandler.sendEmptyMessage(MSG_GONE_ADDRESSNAME);
- }else{
- locPoint=newPoint;
- mHandler.sendEmptyMessage(MSG_VIEW_LONGPRESS);
- }
- }
- };
- mapOverlays=mapView.getOverlays();
- if(mapOverlays.size()>0){
- mapOverlays.clear();
- }
- mapOverlays.add(mOverlay);
- mMapCtrl.setZoom(20);
- }
- privatevoidinitMap(){
- //初始化MapActivity
- mapManager=newBMapManager(getApplication());
- //init方法的第一个参数需填入申请的APIKey
- mapManager.init("C66C0501D0280744759A6957C42543AE38F5D540",null);
- super.initMapActivity(mapManager);
- //实例化搜索地址类
- mMKSearch=newMKSearch();
- //初始化搜索地址实例
- mMKSearch.init(mapManager,newMySearchListener());
- mLocationManager=mapManager.getLocationManager();
- //注册位置更新事件
- mLocationManager.requestLocationUpdates(this);
- //使用GPS定位
- mLocationManager
- .enableProvider((int)MKLocationManager.MK_GPS_PROVIDER);
- }
- @Override
- protectedvoidonResume(){
- if(mapManager!=null){
- mapManager.start();
- }
- super.onResume();
- }
- @Override
- protectedvoidonPause(){
- isLoadAdrr=false;
- if(mapManager!=null){
- mapManager.stop();
- }
- super.onPause();
- }
- @Override
- protectedbooleanisRouteDisplayed(){
- //TODOAuto-generatedmethodstub
- returnfalse;
- }
- /**
- *通过经纬度获取地址
- *
- *@parampoint
- *@return
- */
- privateStringgetLocationAddress(GeoPointpoint){
- Stringadd="";
- GeocodergeoCoder=newGeocoder(getBaseContext(),Locale.getDefault());
- try{
- List<Address>addresses=geoCoder.getFromLocation(
- point.getLatitudeE6()/1E6,point.getLongitudeE6()/1E6,
- 1);
- Addressaddress=addresses.get(0);
- intmaxLine=address.getMaxAddressLineIndex();
- if(maxLine>=2){
- add=address.getAddressLine(1)+address.getAddressLine(2);
- }else{
- add=address.getAddressLine(1);
- }
- }catch(IOExceptione){
- add="";
- e.printStackTrace();
- }
- returnadd;
- }
- privateHandlermHandler=newHandler(){
- @Override
- publicvoidhandleMessage(Messagemsg){
- switch(msg.what){
- caseMSG_VIEW_LONGPRESS://处理长按时间返回位置信息
- {
- if(null==locPoint)
- return;
- mMKSearch.reverseGeocode(locPoint);
- desText.setVisibility(View.VISIBLE);
- desText.setText(lost_tips);
- mMapCtrl.animateTo(locPoint);
- mapView.invalidate();
- }
- break;
- caseMSG_VIEW_ADDRESSNAME:
- desText.setText((String)msg.obj);
- desText.setVisibility(View.VISIBLE);
- break;
- caseMSG_GONE_ADDRESSNAME:
- desText.setVisibility(View.GONE);
- break;
- }
- }
- };
- //关闭程序也关闭定位
- @Override
- protectedvoidonDestroy(){
- if(mapManager!=null){
- mapManager.destroy();
- mapManager=null;
- }
- super.onDestroy();
- }
- /**
- *根据MyLocationOverlay配置的属性确定是否在地图上显示当前位置
- */
- @Override
- protectedbooleanisLocationDisplayed(){
- returnfalse;
- }
- /**
- *当位置发生变化时触发此方法
- *
- *@paramlocation
- *当前位置
- */
- publicvoidonLocationChanged(Locationlocation){
- if(location!=null){
- locPoint=newGeoPoint((int)(location.getLatitude()*1E6),
- (int)(location.getLongitude()*1E6));
- mHandler.sendEmptyMessage(MSG_VIEW_LONGPRESS);
- }
- }
- /**
- *内部类实现MKSearchListener接口,用于实现异步搜索服务
- *
- *@authorliufeng
- */
- publicclassMySearchListenerimplementsMKSearchListener{
- /**
- *根据经纬度搜索地址信息结果
- *
- *@paramresult
- *搜索结果
- *@paramiError
- *错误号(0表示正确返回)
- */
- publicvoidonGetAddrResult(MKAddrInforesult,intiError){
- if(result==null){
- return;
- }
- Messagemsg=newMessage();
- msg.what=MSG_VIEW_ADDRESSNAME;
- msg.obj=result.strAddr;
- mHandler.sendMessage(msg);
- }
- /**
- *驾车路线搜索结果
- *
- *@paramresult
- *搜索结果
- *@paramiError
- *错误号(0表示正确返回)
- */
- publicvoidonGetDrivingRouteResult(MKDrivingRouteResultresult,
- intiError){
- }
- /**
- *POI搜索结果(范围检索、城市POI检索、周边检索)
- *
- *@paramresult
- *搜索结果
- *@paramtype
- *返回结果类型(11,12,21:poi列表7:城市列表)
- *@paramiError
- *错误号(0表示正确返回)
- */
- publicvoidonGetPoiResult(MKPoiResultresult,inttype,intiError){
- }
- /**
- *公交换乘路线搜索结果
- *
- *@paramresult
- *搜索结果
- *@paramiError
- *错误号(0表示正确返回)
- */
- publicvoidonGetTransitRouteResult(MKTransitRouteResultresult,
- intiError){
- }
- /**
- *步行路线搜索结果
- *
- *@paramresult
- *搜索结果
- *@paramiError
- *错误号(0表示正确返回)
- */
- publicvoidonGetWalkingRouteResult(MKWalkingRouteResultresult,
- intiError){
- }
- publicvoidonGetBusDetailResult(MKBusLineResultarg0,intarg1){
- //TODOAuto-generatedmethodstub
- }
- publicvoidonGetSuggestionResult(MKSuggestionResultarg0,intarg1){
- //TODOAuto-generatedmethodstub
- }
- }
- }
五:在AndroidManifest.xml住添加相关的访问权限
<!-- 访问网络的权限 -->
Xml代码- <uses-permissionandroid:name="android.permission.INTERNET"/>
- <!--访问精确位置的权限-->
- <uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION"/>
- <!--访问网络状态的权限-->
- <uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/>
- <!--访问WIFI网络状态的权限-->
- <uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE"/>
- <!--改变WIFI网络状态的权限-->
- <uses-permissionandroid:name="android.permission.CHANGE_WIFI_STATE"/>
- <!--读写存储卡的权限-->
- <uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
- <!--读取电话状态的权限-->
- <uses-permissionandroid:name="android.permission.READ_PHONE_STATE"/>
六:运行结果如下图:
更多相关文章
- Android(安卓)Handler 异步消息处理机制 《第一行代码》
- RMS认为Android没有尊重用户自由
- android2.3 api demo 学习系列(1)--apidemo主列表的实现
- 写给初学者Android(安卓)AIDL必看内容
- Android-sharedUserId数据权限 android:sharedUserId
- Android基于XMPP Smack Openfire开发IM(2)登录openfire
- Android(安卓)Service详解(三) AIDL使用解析
- Android穿山甲SDK激励视频
- Android(安卓)常用的命名规范