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
<span style="white-space:pre">	</span>public void initiLocationUtil (Context context, LocationObsever locationobsever){
		mLocationObsever = locationobsever;
		mContext = context;
		mLocationManager = (LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);
		mLocationListener = new MyLocationListener();
	}
<span style="white-space:pre">		</span>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中增加<uses-library android:name="com.google.android.maps" />

然后xml是:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <include layout="@layout/title_list" />

    <View
        android:id="@+id/line"
        android:layout_width="fill_parent"
        android:layout_height="2dip"
        android:layout_below="@id/title"
        android:background="@drawable/rc_list_divider" />

    <com.google.android.maps.MapView
        android:id="@+id/mapview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:apiKey="06nx-Rzpy8WU16_gjO8ZbtRYYY-junnxNArrxFg" />

</LinearLayout>

代码是:

	@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下载

时间: 2024-10-14 07:49:34

android取得所在位置的经纬度的相关文章

欧美斯项目签到功能,实时获取当前所在位置的经纬度

由于欧美斯项目需要签到功能,因此需要给后台传一个当前位置的经纬度,以下是获取经纬度的方法 1>导入CoreLocation.frameWork 2>引入头文件,并遵循协议 #import <CoreLocation/CoreLocation.h> <CLLocationManagerDelegate> 3>代码 @interface YYAboutUsViewController ()<UIWebViewDelegate,CLLocationManagerD

android百度地图开发之自动定位所在位置与固定位置进行驾车,步行,公交路线搜索

最近跟着百度地图API学地图开发,先是学了路径搜索,对于已知坐标的两点进行驾车.公交.步行三种路径的搜索(公交路径运行没效果,待学习中),后来又 学了定位功能,能够获取到自己所在位置的经纬度,但当将两者合起来先自动获取自己所在位置的经纬度然后与固定地点进行路径搜索时却弄不出来了,因为刚开始 写的两者在两个类中总是取不到经纬度值,后来将两者写到同一个类中去了,终于取到经纬度值了,也运行出来了.需要 在 BDLocationListener的onReceiveLocation里获取到经纬度值,因为已

百度地图定位 : 获取当前位置的经纬度

说明: 1.初始化 BaiduMap SDK要在显示界面之前,即: SDKInitializer.initialize(Context); setContentView(R.layout.main); 2. 设置定位的模式是 LocationMode.Hight_Accuracy 时,在室内可能无法获取到准确的经纬度,会得到默认的值是4.9E-324 处理办法是将模式改为Battery_Saving,或到室外 3.可以根据当前设备网络连接情况和GPS是否开启来设定定位模式 //获得网络连接情况

android EditText插入字符串到光标所在位置

EditText mTextInput=(EditText)findViewById(R.id.input);//EditText对象 int index = mTextInput.getSelectionStart();//获取光标所在位置 String text="I want to input str"; Editable edit = mTextInput.getEditableText();//获取EditText的文字 if (index < 0 || index &

GPS获取Location 获取所在地点的经纬度

利用手机获取所在地点的经纬度: Location 在Android 开发中还是经常用到的,比如 通过经纬度获取天气,根据Location 获取所在地区详细Address (比如Google Map 开发).等.而在Android 中通过LocationManager 来获取Location .通常获取Location 有GPS 获取,WIFI 获取. 如下介绍GPS获取Location: 第一步: 创建一个Android 工程命名为GPS 第二步: 在MainActivity中利用Locatio

EditText插入表情(字符串)到光标所在位置

获取EditText组件 [java] view plaincopy EditText etWeiboContent = (EditText) findViewById(R.id.et_content); 将表情转换成文本 [java] view plaincopy EmoticonsUtil mEmoticons = new EmoticonsUtil(this); CharSequence emoticonsText = mEmoticons.replace(mEmoticons.getEm

获取文件的详细属性,大小,修改日期,所在位置等

asp.net 获得文件属性中的修改时间,获得系统文件属性的方法,最后一次写入时间 1 #region 获取文件的详细属性,大小,修改日期,所在位置等 2 /// <summary> 3 /// 获取文件的详细属性,大小,修改日期,所在位置等 4 /// </summary> 5 /// <param name="files">文件的路径</param> 6 /// <returns></returns> 7 pu

Android PopupWindow显示位置和显示大小

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:bac

当你刷新当前Table时,刷新后如何回到你上一次所在位置呢?

第一: 在你刷新前保存所在位置的行号 procedure XXXClass.LockPositionEx;begin DisableControls; FHistoryRecNo := 0; FHistoryIndexName := EmptyStr; if Active then begin if IndexName <> EmptyStr then FHistoryIndexName := IndexName; IndexName := EmptyStr; if not IsEmpty t