如何在Android中获取GPS位置的地址?

时间:2014-02-06 17:45:32

标签: android gps location geocoding

在我的代码中,我得到了纬度和经度值,但我无法获取我的位置的地址....它只显示地址字段的NULL值...我在清单中提供了所有必需的权限文件,但我仍然没有得到地址..请更正我的代码,并帮助我获取地址值.. 这是我的代码

void getMyCurrentLocation()抛出NullPointerException {

    LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    LocationListener locListener = new MyLocationListener();


     try{gps_enabled=locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
       try{network_enabled=locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

        //don't start listeners if no provider is enabled
        //if(!gps_enabled && !network_enabled)
            //return false;

        if(gps_enabled){
            locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);

        }


        if(gps_enabled){
            location=locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);


        }


        if(network_enabled && location==null){
            locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);

        }


        if(network_enabled && location==null)    {
            location=locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 

        }

    if (location != null) {

       MyLat = location.getLatitude();
        MyLong = location.getLongitude();


    } else {
        Location loc= getLastKnownLocation(this);
        if (loc != null) {

            MyLat = loc.getLatitude();
            MyLong = loc.getLongitude();


        }
    }
    locManager.removeUpdates(locListener); // removes the periodic updates from location listener to //avoid battery drainage. If you want to get location at the periodic intervals call this method using //pending intent.

    try
    {

//从找到的位置获取地址。         地理编码器地理编码器;

    List<Address> addresses;
    geocoder = new Geocoder(this, Locale.getDefault());
     addresses = geocoder.getFromLocation(MyLat, MyLong, 1);

    StateName= addresses.get(0).getAdminArea();
    CityName = addresses.get(0).getLocality();
    CountryName = addresses.get(0).getCountryName();
    // you can get more details other than this . like country code, state code, etc.


    //System.out.println(" StateName " + StateName);
   // System.out.println(" CityName " + CityName);
  //  System.out.println(" CountryName " + CountryName);
    }
    catch (Exception e)
    {
        Toast.makeText(getApplicationContext(), "error"+e,Toast.LENGTH_LONG).show(); 
        e.printStackTrace();
    }

    textView2.setText(""+MyLat);
    textView3.setText(""+MyLong);
    textView1.setText(" StateName " + StateName +" CityName " + CityName +" CountryName " + CountryName);
}

0 个答案:

没有答案