手机自动定位 百度地图API使用的文章

本文介绍了一种在百度地图应用中实现手动触发定位的方法,而非使用自动定位。具体步骤包括获取项目key值、配置必要的文件、设计布局界面、编写定位代码等。文中还提供了关键代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近由于项目需要,研究了下百度地图定位,他们提供的实例基本都是用监听器实现自动定位的。我想实现一种效果:当用户进入UI时,不定位,用户需要定位的时候,自己手动点击按钮,再去定位当前位置。 经过2天研究和咨询,找到了解决方案,在此备忘一下。

注意:定位使用真机才能够真正定位;模拟器的话,在DDMS中的Emulator Control中,选择Manual,下面单选按钮选择Decimal,然后填写经纬度,send后,再点击定位我的位置按钮,就能定位了(这应该算是固定定位,哈哈。。。)、

1、第一步当然是获取一个针对自己项目的key值。http://dev.baidu.com/wiki/static/imap/key/

2、使用百度API是有前提的,摘自百度:首先将API包括的两个文件baidumapapi.jar和libBMapApiEngine.so拷贝到工程根目录及libs\armeabi目录下,并在工程属性->Java Build Path->Libraries中选择“Add JARs”,选定baidumapapi.jar,确定后返回,这样您就可以在您的程序中使用API了。(这两个文件见附件)。

3、按照自己的需求写一个layout,我的如下:

<?xml version="1.0" encoding="utf-8"?>

Xml代码 复制代码 收藏代码
  1. <LinearLayout
  2. xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <TextView
  8. android:id="@+id/myLocation_id"
  9. android:layout_width="fill_parent"
  10. android:layout_height="wrap_content"
  11. android:textSize="15dp"
  12. android:gravity="center_horizontal"
  13. android:textColor="@drawable/black"
  14. android:background="@drawable/gary"
  15. />
  16. <com.baidu.mapapi.MapViewandroid:id="@+id/bmapsView"
  17. android:layout_width="fill_parent"android:layout_height="fill_parent"
  18. android:clickable="true"android:layout_weight="1"
  19. />
  20. <Button
  21. android:layout_width="wrap_content"
  22. android:layout_height="wrap_content"
  23. android:id="@+id/location_button_id"
  24. android:text="@string/location_button_text"
  25. />
  26. </LinearLayout>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  
  <TextView 
  	android:id="@+id/myLocation_id" 
  	android:layout_width="fill_parent" 
  	android:layout_height="wrap_content"
  	android:textSize="15dp"
  	android:gravity="center_horizontal"
  	android:textColor="@drawable/black"
  	android:background="@drawable/gary"
  	/>
  	
  <com.baidu.mapapi.MapView android:id="@+id/bmapsView"
	android:layout_width="fill_parent" android:layout_height="fill_parent" 
	android:clickable="true"  android:layout_weight="1"   
   />
  
  <Button 
	  android:layout_width="wrap_content" 
	  android:layout_height="wrap_content" 
	  android:id="@+id/location_button_id" 
	  android:text="@string/location_button_text"
   />
    
</LinearLayout>

需要特别注意的是:<com.baidu.mapapi.MapView /> 这玩意。

4、写一个MapApplication实现application,提供全局的BMapManager,以及其初始化。

Java代码 复制代码 收藏代码
  1. publicBMapManagermapManager=null;
  2. staticMapApplicationapp;
  3. publicStringmStrKey="你申请的key值";
  4. @Override
  5. publicvoidonCreate(){
  6. mapManager=newBMapManager(this);
  7. mapManager.init(mStrKey,newMyGeneralListener());
  8. }
  9. @Override
  10. //建议在您app的退出之前调用mapadpi的destroy()函数,避免重复初始化带来的时间消耗
  11. publicvoidonTerminate(){
  12. //TODOAuto-generatedmethodstub
  13. if(mapManager!=null)
  14. {
  15. mapManager.destroy();
  16. mapManager=null;
  17. }
  18. super.onTerminate();
  19. }
  20. staticclassMyGeneralListenerimplementsMKGeneralListener{
  21. @Override
  22. publicvoidonGetNetworkState(intarg0){
  23. Toast.makeText(MapApplication.app.getApplicationContext(),"您的网络出错啦!",
  24. Toast.LENGTH_LONG).show();
  25. }
  26. @Override
  27. publicvoidonGetPermissionState(intiError){
  28. if(iError==MKEvent.ERROR_PERMISSION_DENIED){
  29. //授权Key错误:
  30. Toast.makeText(MapApplication.app.getApplicationContext(),"您的授权Key不正确!",
  31. Toast.LENGTH_LONG).show();
  32. }
  33. }
  34. }
  35. 5、接下来就是按照百度api写定位代码了,使用handler机制去添加定位图层,需要说明的都在注释上了。
  36. privateBMapManagermBMapMan=null;
  37. privateMapViewmMapView=null;
  38. privateMapControllerbMapController;
  39. privateMKLocationManagermkLocationManager;
  40. privateMKSearchmkSearch;
  41. privateTextViewaddress_view;//定位到的位置信息
  42. privateProgressDialogdialog;
  43. privateList<HotelInfo>hotelList;
  44. privateintdistance=1000;//查询的范围(单位:m)
  45. Handlerhandler=newHandler(){
  46. @Override
  47. publicvoidhandleMessage(Messagemsg){
  48. doublelat=msg.getData().getDouble("lat");
  49. doublelon=msg.getData().getDouble("lon");
  50. if(lat!=0&&lon!=0){
  51. GeoPointpoint=newGeoPoint(
  52. (int)(lat*1E6),
  53. (int)(lon*1E6));
  54. bMapController.animateTo(point);//设置地图中心点
  55. bMapController.setZoom(15);
  56. mkSearch.reverseGeocode(point);//解析地址(异步方法)
  57. MyLocationOverlaymyLoc=newMyLocationOverlayFromMap(ShowMapAct.this,mMapView);
  58. myLoc.enableMyLocation();//启用定位
  59. myLoc.enableCompass();//启用指南针
  60. mMapView.getOverlays().add(myLoc);
  61. }else{
  62. Toast.makeText(ShowMapAct.this,"没有加载到您的位置",Toast.LENGTH_LONG).show();
  63. }
  64. if(hotelList!=null){
  65. Drawablemarker=getResources().getDrawable(R.drawable.iconmarka);//设置marker
  66. marker.setBounds(0,0,marker.getIntrinsicWidth(),marker.getIntrinsicHeight());//为maker定义位置和边界
  67. mMapView.getOverlays().add(newOverItemList(marker,hotelList,ShowMapAct.this,bMapController));
  68. }elseif(hotelList==null&&lat!=0&&lon!=0){
  69. Toast.makeText(ShowMapAct.this,"网络异常,没有获取到酒店信息。",Toast.LENGTH_LONG).show();
  70. }
  71. if(dialog!=null)dialog.dismiss();
  72. }
  73. };
  74. @Override
  75. protectedvoidonCreate(BundlesavedInstanceState){
  76. distance=getIntent().getExtras().getInt("distance");//获取查询范围
  77. super.onCreate(savedInstanceState);
  78. setContentView(R.layout.location);
  79. mMapView=(MapView)findViewById(R.id.bmapsView);//初始化一个mapView存放Map
  80. init();//初始化地图管理器
  81. super.initMapActivity(mBMapMan);
  82. address_view=(TextView)findViewById(R.id.myLocation_id);
  83. SpannableStringBuilderstyle=newSpannableStringBuilder(String.format(getResources().getString(R.string.location_text),"位置不详"));
  84. style.setSpan(newForegroundColorSpan(Color.RED),5,style.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  85. address_view.setText(style);
  86. Buttonlocation_button=(Button)findViewById(R.id.location_button_id);
  87. location_button.setOnClickListener(newView.OnClickListener(){
  88. @Override
  89. publicvoidonClick(Viewv){
  90. dialog=ProgressDialog.show(ShowMapAct.this,"","数据加载中,请稍后.....");
  91. newThread(newMyThread()).start();
  92. }
  93. });
  94. mkSearch=newMKSearch();//初始化一个MKSearch,根据location解析详细地址
  95. mkSearch.init(mBMapMan,this);
  96. mMapView.setBuiltInZoomControls(true);//启用内置的缩放控件
  97. bMapController=mMapView.getController();
  98. GeoPointdefaultPoint=newGeoPoint((int)(39.920934*1E6),(int)(116.412817*1E6));//用给定的经纬度构造一个GeoPoint,单位是微度(度*1E6)
  99. bMapController.setCenter(defaultPoint);//设置地图中心点
  100. bMapController.setZoom(12);//设置地图zoom级别
  101. mkLocationManager=mBMapMan.getLocationManager();
  102. }
  103. /**
  104. *初始化地图管理器BMapManager
  105. */
  106. publicvoidinit(){
  107. MapApplicationapp=(MapApplication)getApplication();
  108. if(app.mapManager==null){
  109. app.mapManager=newBMapManager(getApplication());
  110. app.mapManager.init(app.mStrKey,newMapApplication.MyGeneralListener());
  111. }
  112. mBMapMan=app.mapManager;
  113. }
  114. @Override
  115. protectedvoidonDestroy(){
  116. MapApplicationapp=(MapApplication)getApplication();
  117. if(mBMapMan!=null){
  118. mBMapMan.destroy();
  119. app.mapManager.destroy();
  120. app.mapManager=null;
  121. mBMapMan=null;
  122. }
  123. super.onDestroy();
  124. }
  125. @Override
  126. protectedvoidonPause(){
  127. if(mBMapMan!=null){
  128. //终止百度地图API
  129. mBMapMan.stop();
  130. }
  131. super.onPause();
  132. }
  133. @Override
  134. protectedvoidonResume(){
  135. if(mBMapMan!=null){
  136. //开启百度地图API
  137. mBMapMan.start();
  138. }
  139. super.onResume();
  140. }
  141. @Override
  142. protectedbooleanisRouteDisplayed(){
  143. returnfalse;
  144. }
  145. @Override
  146. publicvoidonGetAddrResult(MKAddrInforesult,intiError){
  147. if(result==null)return;
  148. SpannableStringBuilderstyle=newSpannableStringBuilder(String.format(getResources().getString(R.string.location_text),result.strAddr));
  149. style.setSpan(newForegroundColorSpan(Color.RED),5,style.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  150. address_view.setText(style);
  151. if(dialog!=null)dialog.dismiss();
  152. }
  153. @Override
  154. publicvoidonGetDrivingRouteResult(MKDrivingRouteResultarg0,intarg1){}
  155. @Override
  156. publicvoidonGetPoiResult(MKPoiResultarg0,intarg1,intarg2){}
  157. @Override
  158. publicvoidonGetTransitRouteResult(MKTransitRouteResultarg0,intarg1){}
  159. @Override
  160. publicvoidonGetWalkingRouteResult(MKWalkingRouteResultarg0,intarg1){}
  161. /**
  162. *重新定位,加载数据
  163. *@authorAdministrator
  164. *
  165. */
  166. classMyThreadimplementsRunnable{
  167. @Override
  168. publicvoidrun(){
  169. /**
  170. *最重要的就是这个玩意
  171. *由于LocationListener获取第一个位置修正的时间会很长,为了避免用户等待,
  172. *在LocationListener获取第一个更精确的位置之前,应当使用getLocationInfo()获取一个缓存的位置
  173. */
  174. Locationlocation=mkLocationManager.getLocationInfo();
  175. doublelat=0d,lon=0d;
  176. if(location!=null){//定位到位置
  177. Stringcoordinate=location.getLatitude()+","+location.getLongitude();
  178. HotelRemoteDatahotelData=newHotelRemoteData();
  179. /**
  180. *远程获取酒店列表数据
  181. */
  182. hotelList=hotelData.getHotelToMap(coordinate,distance);
  183. lat=location.getLatitude();
  184. lon=location.getLongitude();
  185. }
  186. Messagemsg=newMessage();
  187. Bundledata=newBundle();
  188. data.putDouble("lat",lat);
  189. data.putDouble("lon",lon);
  190. msg.setData(data);
  191. handler.sendMessage(msg);
  192. }
  193. }
 public BMapManager mapManager = null;
	static MapApplication app;
	public String mStrKey = "你申请的key值";
	
	@Override
	public void onCreate() {
		mapManager = new BMapManager(this);
		mapManager.init(mStrKey, new MyGeneralListener());
	}
	@Override
	//建议在您app的退出之前调用mapadpi的destroy()函数,避免重复初始化带来的时间消耗
	public void onTerminate() {
		// TODO Auto-generated method stub
		if(mapManager != null)
		{
			mapManager.destroy();
			mapManager = null;
		}
		super.onTerminate();
	}

	 static class MyGeneralListener implements MKGeneralListener{

		@Override
		public void onGetNetworkState(int arg0) {
			Toast.makeText(MapApplication.app.getApplicationContext(), "您的网络出错啦!",
					Toast.LENGTH_LONG).show();
		}
		@Override
		public void onGetPermissionState(int iError) {
			if (iError ==  MKEvent.ERROR_PERMISSION_DENIED) {
				// 授权Key错误:
				Toast.makeText(MapApplication.app.getApplicationContext(),"您的授权Key不正确!",
						Toast.LENGTH_LONG).show();
			}
		}
	}
	5、接下来就是按照百度api写定位代码了,使用handler机制去添加定位图层,需要说明的都在注释上了。

        private BMapManager mBMapMan = null;
	private MapView mMapView = null;
	private MapController bMapController;
	private MKLocationManager mkLocationManager;
	private MKSearch mkSearch;
	
	private TextView address_view;   //定位到的位置信息
	
	private ProgressDialog dialog;
	private List<HotelInfo> hotelList;
	
	private int distance = 1000;  //查询的范围(单位:m)
	
    Handler handler = new Handler(){
	   	@Override
	   	public void handleMessage(Message msg) {
	   		
	   		double lat = msg.getData().getDouble("lat");
	   		double lon = msg.getData().getDouble("lon");
	   		if(lat!=0&&lon!=0){
	   			GeoPoint point = new GeoPoint(
	   					(int) (lat * 1E6),
						(int) (lon * 1E6));
	   		    bMapController.animateTo(point);  //设置地图中心点
	   		    bMapController.setZoom(15);
	   		    
	   		    mkSearch.reverseGeocode(point);   //解析地址(异步方法)
	   		    
	   			MyLocationOverlay myLoc = new MyLocationOverlayFromMap(ShowMapAct.this,mMapView);
		        myLoc.enableMyLocation(); 	// 启用定位
		        myLoc.enableCompass();    	// 启用指南针
		        mMapView.getOverlays().add(myLoc);
	   		}else{
	   			Toast.makeText(ShowMapAct.this, "没有加载到您的位置", Toast.LENGTH_LONG).show();
	   		}
	   		
	        if(hotelList!=null){
	    		Drawable marker = getResources().getDrawable(R.drawable.iconmarka);  //设置marker
	 	        marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());   //为maker定义位置和边界
	    		mMapView.getOverlays().add(new OverItemList(marker,hotelList,ShowMapAct.this,bMapController));
	    	}else if(hotelList==null&&lat!=0&&lon!=0){
	    		Toast.makeText(ShowMapAct.this, "网络异常,没有获取到酒店信息。", Toast.LENGTH_LONG).show();
	    	}
			if(dialog!=null)  dialog.dismiss();
	   	}
   };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		distance = getIntent().getExtras().getInt("distance");   //获取查询范围
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.location);
		
		mMapView = (MapView)findViewById(R.id.bmapsView);   //初始化一个mapView  存放Map
		init();  //初始化地图管理器
		super.initMapActivity(mBMapMan);
		
		
		address_view = (TextView)findViewById(R.id.myLocation_id);
		SpannableStringBuilder style = new SpannableStringBuilder(String.format(getResources().getString(R.string.location_text),"位置不详"));
		style.setSpan(new ForegroundColorSpan(Color.RED), 5, style.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		address_view.setText(style);
		
		Button location_button = (Button)findViewById(R.id.location_button_id);
		location_button.setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v) {
				 dialog = ProgressDialog.show(ShowMapAct.this, "", "数据加载中,请稍后.....");
				 new Thread(new MyThread()).start();
			}
		});
		
		mkSearch = new MKSearch();   //初始化一个MKSearch,根据location解析详细地址
		mkSearch.init(mBMapMan, this);
        mMapView.setBuiltInZoomControls(true);   //启用内置的缩放控件
        bMapController = mMapView.getController();
        GeoPoint defaultPoint = new GeoPoint((int) (39.920934 * 1E6),(int) (116.412817 * 1E6));  //用给定的经纬度构造一个GeoPoint,单位是微度 (度 * 1E6)
        bMapController.setCenter(defaultPoint);  //设置地图中心点
        bMapController.setZoom(12);  //设置地图zoom级别
        
        mkLocationManager = mBMapMan.getLocationManager();
	}
	/**
	 * 初始化地图管理器BMapManager
	 */
	public void init(){
		MapApplication app = (MapApplication)getApplication();
        if (app.mapManager == null) {
        	app.mapManager = new BMapManager(getApplication());
        	app.mapManager.init(app.mStrKey, new MapApplication.MyGeneralListener());
        }
        mBMapMan = app.mapManager;
	}
	
	@Override
	protected void onDestroy() {
		MapApplication app = (MapApplication)getApplication();
		if (mBMapMan != null) {
			mBMapMan.destroy();
			app.mapManager.destroy();
			app.mapManager = null;
			mBMapMan = null;
		}
		super.onDestroy();
	}
	
  
    @Override  
    protected void onPause() {  
        if (mBMapMan != null) {  
            // 终止百度地图API  
        	mBMapMan.stop();  
        }  
        super.onPause();  
    }
  
    @Override  
    protected void onResume() {
        if (mBMapMan != null) {  
            // 开启百度地图API  
        	mBMapMan.start();  
        }  
        super.onResume();  
    }
	
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
	@Override
	public void onGetAddrResult(MKAddrInfo result, int iError) {
		if(result==null) return;
		SpannableStringBuilder style = new SpannableStringBuilder(String.format(getResources().getString(R.string.location_text),result.strAddr));
		style.setSpan(new ForegroundColorSpan(Color.RED), 5, style.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		address_view.setText(style);
		if(dialog!=null) dialog.dismiss();
	}
	
	@Override
	public void onGetDrivingRouteResult(MKDrivingRouteResult arg0, int arg1) {}
	@Override
	public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2) {}
	@Override
	public void onGetTransitRouteResult(MKTransitRouteResult arg0, int arg1) {}
	@Override
	public void onGetWalkingRouteResult(MKWalkingRouteResult arg0, int arg1) {}
	
	/**
	 * 重新定位,加载数据
	 * @author Administrator
	 *
	 */
	class MyThread implements Runnable{
		@Override
		public void run() {
			/**
			  * 最重要的就是这个玩意
			  * 由于LocationListener获取第一个位置修正的时间会很长,为了避免用户等待,
			  * 在LocationListener获取第一个更精确的位置之前,应当使用getLocationInfo() 获取一个缓存的位置
			  */
		    Location location = mkLocationManager.getLocationInfo();
		    double lat = 0d,lon = 0d;
			if(location!=null){   //定位到位置
				String coordinate = location.getLatitude()+","+location.getLongitude();
				HotelRemoteData hotelData = new HotelRemoteData();
				/**
				 * 远程获取酒店列表数据
				 */
		    	hotelList = hotelData.getHotelToMap(coordinate,distance);
	        	lat = location.getLatitude();
	        	lon = location.getLongitude();
			}
			
        	Message msg = new Message();
        	Bundle data = new Bundle();
        	data.putDouble("lat", lat);
        	data.putDouble("lon", lon);
        	msg.setData(data);
        	handler.sendMessage(msg);
		}
	}

6、还有一种就是百度示例相当推荐的,也是加载定位位置速度比较快的,那就是通过定位监听器来定位信息。没啥难的,照着百度的示例写,都能搞定。

Java代码 复制代码 收藏代码
  1. LocationListenerlistener=newLocationListener(){
  2. @Override
  3. /**位置变化,百度地图即会调用该方法去获取位置信息。
  4. *(我测试发现就算手机不动,它也会偶尔重新去加载位置;只要你通过重力感应,他就一定会重新加载)
  5. */
  6. publicvoidonLocationChanged(Locationlocation){
  7. GeoPointgp=newGeoPoint((int)(location.getLatitude()*1E6),(int)(location.getLongitude()*1E6));//通过地图上的经纬度转换为地图上的坐标点
  8. bMapController.animateTo(gp);//动画般的移动到定位的位置
  9. }
  10. };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值