Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android取得所在位置的經緯度

android取得所在位置的經緯度

編輯:關於Android編程

android提供了LocationManager來取得位置,用LocationListener來監聽位置的變化

先做一些初始化工作:

/** latitude and longitude of current location*/
	public static String mLat = "";
	public static String mLon = "";

	/** time out for GPS location update */
	private  Timer mGpsTimer = new Timer();	
	/** TimerTask for time out of GPS location update */
	private  GpsTimeOutTask mGpsTimeOutTask = new GpsTimeOutTask();
	/** GPS location update time out in milliseconds*/
	private  long mGpsTimeOut = 180000;//3 minutes
	public void initiLocationUtil (Context context, LocationObsever locationobsever){
		mLocationObsever = locationobsever;	
		mContext = context;
		mLocationManager = (LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);	
		mLocationListener = new MyLocationListener();	
	}


		public void RefreshGPS(boolean calledByCreate){	
		
		mLocationManager.removeUpdates(mLocationListener);
		boolean providerEnable = true;
		boolean showLocationServiceDisableNotice = true;
		//看是否有GPS權限
		if(mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
			//開始進行定位 mLocationListener為位置監聽器
			mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
					0, 
					0, 
					mLocationListener);
			showLocationServiceDisableNotice = false;
			
			//start time out timer 
			mGpsTimer = new Timer(); 
			mGpsTimeOutTask = new GpsTimeOutTask();
			mGpsTimer.schedule(mGpsTimeOutTask, mGpsTimeOut);
			
		}
		
		if(mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
			mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 
					0, 
					0, 
					mLocationListener);
			showLocationServiceDisableNotice = false;
			providerEnable = true;
		}
				
		if(providerEnable){
			if(mLocationObsever != null){
				mLocationObsever.notifyChange(REFRESHGPS_COMPLETED, null);
			}

		}else{
			if(mLocationObsever != null){
				mLocationObsever.notifyChange(REFRESHGPS_NOPROVIDER, null);
			}

		}
		
		if(showLocationServiceDisableNotice){
			showLocationServiceDisabledDialog();
		}
		
	}


監聽器:

private  class MyLocationListener implements LocationListener{
		private boolean mLocationReceived = false;
		@Override
		public void onLocationChanged(Location location) {
			if(location != null && !mLocationReceived){
				mLocationReceived = true;
				String lon = String.valueOf(location.getLongitude());
				String lat = String.valueOf(location.getLatitude());	
				if(mLocationObsever != null){
					mLocationObsever.notifyChange(DEFAULT_LOCATION_COMPLETED, lat+","+lon);
				}
			}else  if(location == null){
				if(mLocationObsever != null){
					mLocationObsever.notifyChange(GETLOCATION_FAILED, null);	
				}
			}
		}

		@Override
		public void onProviderDisabled(String provider) {
			
		}

		@Override
		public void onProviderEnabled(String provider) {
			
		}

		@Override
		public void onStatusChanged(String provider, int status,
				Bundle extras) {
			// TODO Auto-generated method stub
			//if GPS provider is not accessible, try network provider
			if(provider.equals(LocationManager.GPS_PROVIDER) && status != LocationProvider.AVAILABLE){
				if(mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
					mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 
							0, 
							0, 
							mLocationListener);
				}else{
					mLocationManager.removeUpdates(mLocationListener);

					if(mLocationObsever != null){
						mLocationObsever.notifyChange(STATUS_CHANGED, null);
					}
				}
			}
		}
	}


這裡用了一個Timer,3分鐘後重新去取一次位置:

	private Handler mGpsTimerHandler = new Handler() {
		public void handleMessage(Message msg) {

			if (mLocationManager == null) {
				return;
			}
			if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
				System.out.println("=====use network to get location");
				mLocationManager.requestLocationUpdates(
						LocationManager.NETWORK_PROVIDER, 0, 0,
						mLocationListener);
			} else {
				mLocationManager.removeUpdates(mLocationListener);

				// mLocationObsever.notifyChange(SETADDLOCATIONBUTTONSTATE_1_SETLOCATIONDES_1,null);
				if (mLocationObsever != null) {
					mLocationObsever.notifyChange(GPSTIMEOUT, null);
				}
			}
		}
	};

界面退出的時候要關掉GPS

	/**
	 * cancel operations of refreshing GPS
     */
	public  void cancelRefreshGPS(){
		if(mLocationManager != null){
			mLocationManager.removeUpdates(mLocationListener);
		}
		
		if(mLocationObsever != null){
			mLocationObsever.notifyChange(CANCELGPS_COMPLETED, null);	
		}
	}	
	
	
	
	public  void destroy (){
		if(mLocationManager != null){
		     mLocationManager.removeUpdates(mLocationListener);
		}
		
		if(mGpsTimer != null){
			mGpsTimer.cancel();
		} 
		
		cancelRefreshGPS();
		
		mContext = null;
		mLocationObsever = null;
		
		mLocationBuildingList = null;
		
		System.gc();
	}

截圖是

\


點擊MAP的時候,如果采用google map,必須使用sdk帶有google api,然後在application中加入

然後xml是:




    

    

    


代碼是:

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.around_map);
		mTextView = (TextView)findViewById(R.id.title_text);
		mTextView.setText("地圖");
		
		Intent intent = getIntent();
		mLatitude = intent.getDoubleExtra("lat", 0.0);
		mLongitude = intent.getDoubleExtra("lon", 0.0);
		
		mMapView = (MapView) findViewById(R.id.mapview);  	    
		mMapView.setClickable(true);  	    
		mMapView.setBuiltInZoomControls(true);		
		mMapView.setSatellite(true);
	    mapController = mMapView.getController();
//	    geoPoint = new GeoPoint((int)(mLatitude * 1E6), (int)(mLongitude * 1E6));  
	    geoPoint=new GeoPoint((int)(30.659259*1000000),(int)(104.065762*1000000));
	    mMapView.displayZoomControls(true); 
	    
//	    //  設置地圖的初始大小,范圍在1和21之間。1:最小尺寸,21:最大尺寸
	    mapController.setZoom(16);
//	    
//	//  創建MyOverlay對象,用於在地圖上繪制圖形  
	    MyOverlay myOverlay = new MyOverlay();  
	    mMapView.getOverlays().add(myOverlay);  	       
	    mapController.animateTo(geoPoint);  
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
	class MyOverlay extends Overlay  
	{  
	    @Override  
	    public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when)  
	    {  
	        Paint paint = new Paint();  
	        
	        //屏幕上文字字體顏色
	        paint.setColor(Color.RED);  
	        Point screenPoint = new Point();  
	          
	        mapView.getProjection().toPixels(geoPoint, screenPoint);  
	        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.location);  
	        //  在地圖上繪制圖像  
	        canvas.drawBitmap(bmp, screenPoint.x, screenPoint.y, paint);  
	        //  在地圖上繪制文字  
//	        canvas.drawText("移動巴士", 10, 100, paint);  
	        return super.draw(canvas, mapView, shadow, when);  
	    }  
	} 


代碼可以在http://download.csdn.net/detail/baidu_nod/7622677下載


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved