纬度和经度的当前位置

时间:2013-12-16 11:30:45

标签: android geocoding

我正在为getAddress()和address()使用两种方法..一个用于获取纬度,另一个用于从纬度和经度获取地址..

       public String  getAddress(){

       location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
       location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);

            latitude= location.getLatitude();
            longitude= location.getLongitude();

        try {
            val = address(latitude, longitude);
            } catch (IOException e) {

            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;
    }       

使用InitializeMap()获取当前位置:

    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();
        }
    }
}

完整的代码如下,但问题是没有获取地址:

 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,val1;
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());

      val1 = getAddress();


        // Loading map
        initilizeMap();

}

/**
 * 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);

            latitude= location.getLatitude();
            longitude= location.getLongitude();

        try {
            val = address(latitude, longitude);
            } catch (IOException e) {

            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(CurrentLoc.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();
    }

    }



@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
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(){

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

            intnt.putExtra("loct", val1);

            startActivity(intnt); 
        }

}

2 个答案:

答案 0 :(得分:1)

首先你要做谷歌搜索:

喜欢这样:Googling

您将获得以下链接:

Displaying a Location Address

答案 1 :(得分:0)

使用以下代码使用geocode获取地址。确保您在INTERNET

中拥有androidManifest.xml权限
List<Address> addressList = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            StringBuilder stringBuilder = new StringBuilder();
            if (addressList.size() > 0) {
                Address address = addressList.get(0);
                for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                    stringBuilder.append(address.getAddressLine(i)).append("\n");
                    stringBuilder.append(address.getLocality()).append("\n");
                    stringBuilder.append(address.getPostalCode()).append("\n");
                    stringBuilder.append(address.getCountryName()).append("\n");
                }

                addressString = stringBuilder.toString();

            }