获取当前位置..在地图上很好..但没有得到地址

时间:2013-12-16 08:36:20

标签: android android-actionbar geocoding

实际上我正在使用地理编码器来获取地址..但我得到的地址值为null。据我所知,我写了正确的代码来从getAddress()和address()等方法获取当前位置。我使用的代码如下:

public class CurrentLoc extends Activity {

// latitude and longitude
static double latitude ;
static double longitude ;

  // Google Map
private GoogleMap googleMap;
private LocationManager locationManager;
private Location location;
private String val;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.new3);
    locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
      locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 
                MINIMUM_TIME_BETWEEN_UPDATES, 
                MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
                new MyLocationListener()
        );  
      locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());

        getAddress();

    try {
        // Loading map
        initilizeMap();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

/**
 * function to load map. If map is not created it will create it for you
 * */

public String  getAddress(){

       location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
       location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
        if (location != null) {
            latitude= location.getLatitude();
            longitude= location.getLongitude();

            /*String message = String.format(
                    "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                    lat, lng);*/


        try {
            val = address(latitude, longitude);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


            Toast.makeText( CurrentLoc.this, val,
                    Toast.LENGTH_LONG).show();
        }
        return val;
    }      

    public String address(double lt,double lg) throws IOException{
        Geocoder geocoder;
        List<Address> addresses;
        geocoder = new Geocoder(this, Locale.getDefault());
        addresses = geocoder.getFromLocation(lt, lg, 1);

        String address = addresses.get(0).getAddressLine(0);
        String city = addresses.get(0).getAddressLine(1);
        String country = addresses.get(0).getAddressLine(2);
        return address +"\n"+ city +"\n"+ country;
    }       






    private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        String message = String.format(
                "New Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
     //   Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
    }

    public void onStatusChanged(String s, int i, Bundle b) {
        Toast.makeText(CurrentLoc.this, "Provider status changed",
               Toast.LENGTH_LONG).show();
    }

    public void onProviderDisabled(String s) {
        Toast.makeText(CurrentLoc.this,
                "Provider disabled by the user. GPS turned off",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderEnabled(String s) {
        Toast.makeText(CurrentLoc.this,
                "Provider enabled by the user. GPS turned on",
                Toast.LENGTH_LONG).show();
    }

    }



private void initilizeMap() {
    if (googleMap == null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();

        CameraPosition cameraPosition = new CameraPosition.Builder().target(
                new LatLng(location.getLatitude(), location.getLongitude())).zoom(12).build();

googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        MarkerOptions marker = new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("Hello Maps ");
        googleMap.addMarker(marker);
        googleMap.isMyLocationEnabled();
        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}


        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.mnew1, menu);

            return super.onCreateOptionsMenu(menu);
        }
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle presses on the action bar items
            switch (item.getItemId()) {
                case R.id.home:

                    openSearch();

                    return true;          
            default:
                    return super.onOptionsItemSelected(item);
            }
            }

        private void openSearch(){

            String val1 = null;

                val1 = getAddress();

            Intent intnt=new Intent(getApplicationContext(),SendSms.class);

            intnt.putExtra("loct", val1);
            startActivity(intnt); 
        }

}

1 个答案:

答案 0 :(得分:0)

移动你的代码:

if (location != null) {
    latitude= location.getLatitude();
    longitude= location.getLongitude();

    value=address(latitude, longitude);

    Toast.makeText( CurrentLoc.this, value,
    Toast.LENGTH_LONG).show();
 }

public void onLocationChanged(Location location)方法内。

当您申请新位置时,您不会立即得到结果。相反,您需要注册一个侦听器,就像调用locationManager.requestLocationUpdates时一样,这样位置提供程序可以在为您提取位置时通知它。

此外,根据我的代码理解,如果您只需要在当前位置获取手机地址,而不是经常获取locationManager.requestSingleUpdate将提供的位置更新,您可以通过拨打requestLocationUpdates而受益你。

最后,请考虑此blog post以获取有关获取用户位置的最佳做法。如果当前位置已知,则您并不总是需要获取位置更新。

希望它有所帮助。