我怎样才能获得当前位置并显示城市名称

时间:2015-03-09 10:22:31

标签: java android google-maps geomap

我是android创建当前位置的新手并显示其城市名称

我不知道代码所以举一些例子来创建当前位置并提前显示城市名称

2 个答案:

答案 0 :(得分:0)

使用此代码从纬度经度获取位置名称

Geocoder geocoder;
        List<Address> addresses;
        geocoder = new Geocoder(context, Locale.getDefault());
            try {
                addresses = geocoder.getFromLocation(lat, lng, 1);
                if(addresses.size()>0)
                {
                String cityName = addresses.get(0).getAddressLine(0);
                 String stateName = addresses.get(0).getAddressLine(1);
                 //Toast.makeText(getApplicationContext(),stateName , 1).show();
                 String countryName = addresses.get(0).getAddressLine(2);
                 }
            }catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

获取当前位置的纬度和经度使用以下步骤:

  • 在项目名称中创建新类GPSTracker.java
  • 将下面的代码复制并粘贴到其中

    公共类GPSTracker扩展服务实现LocationListener {

    private final Context mContext;
    
    // flag for GPS status
    boolean isGPSEnabled = false;
    
    // flag for network status
    boolean isNetworkEnabled = false;
    
    // flag for GPS status
    boolean canGetLocation = false;
    
     Location location; // location
      double latitude=0;// latitude
       double longitude=0; // longitude
    
    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
    
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
    
    // Declaring a Location Manager
    protected LocationManager locationManager;
    
    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }
    
    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);
    
            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
    
            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        Log.v("location ",""+location);
    
    
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            Log.v("location ",""+location);
    
    
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return location;
    }
    
    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }      
    }
    
    /**
     * Function to get latitude
     * */
    public  double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }
    
        // return latitude
        return latitude;
    }
    
    /**
     * Function to get longitude
     * */
    public  double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }
    
        // return longitude
        return longitude;
    }
    
    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }
    

    @覆盖 public void onLocationChanged(Location location){     // TODO自动生成的方法存根

    }

    @覆盖 public void onProviderDisabled(String provider){     // TODO自动生成的方法存根

    }

    @覆盖 public void onProviderEnabled(String provider){     // TODO自动生成的方法存根

    }

    @覆盖 public void onStatusChanged(String provider,int status,Bundle extras){     // TODO自动生成的方法存根

    }

    @覆盖 public IBinder onBind(Intent arg0){     // TODO自动生成的方法存根     return null; } }

  • 现在,您想要获得纬度和经度,请使用以下代码:

    GPSTracker mTracker =新的GPSTracker(MyActivity.this); double lat = mTracker.getLatitude(); double lng = mTracker.getLongitude();

答案 1 :(得分:0)

public class MainActivity extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener
{
   LocationClient mLocationClient;
private TextView addressLabel;
private TextView locationLabel;
private Button getLocationBtn;
private Button disconnectBtn;
private Button connectBtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  locationLabel = (TextView) findViewById(R.id.locationLabel);
  addressLabel = (TextView) findViewById(R.id.addressLabel);
  getLocationBtn = (Button) findViewById(R.id.getLocation);

  getLocationBtn.setOnClickListener(new View.OnClickListener() {
     public void onClick(View view) {
        displayCurrentLocation();
     }
  });
  disconnectBtn = (Button) findViewById(R.id.disconnect);  
  disconnectBtn.setOnClickListener(new View.OnClickListener() {
     public void onClick(View view) {
        mLocationClient.disconnect();
        locationLabel.setText("Got disconnected....");
     }
  });
  connectBtn = (Button) findViewById(R.id.connect);  
  connectBtn.setOnClickListener(new View.OnClickListener() {
     public void onClick(View view) {
        mLocationClient.connect();
        locationLabel.setText("Got connected....");
     }
  });   
  // Create the LocationRequest object
   mLocationClient = new LocationClient(this, this, this);  
 }  
 @Override
 protected void onStart() {
  super.onStart();
  // Connect the client.
  mLocationClient.connect();
  locationLabel.setText("Got connected....");
}
@Override
protected void onStop() {
  // Disconnect the client.
  mLocationClient.disconnect();
  super.onStop();
  locationLabel.setText("Got disconnected....");
  }
  @Override
  public void onConnected(Bundle dataBundle) {
  // Display the connection status
  Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
}
@Override
public void onDisconnected() {
  // Display the connection status
  Toast.makeText(this, "Disconnected. Please re-connect.",
  Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
  // Display the error code on failure
  Toast.makeText(this, "Connection Failure : " + 
  connectionResult.getErrorCode(),
  Toast.LENGTH_SHORT).show();
}
public void displayCurrentLocation() {
  // Get the current location's latitude & longitude
  Location currentLocation = mLocationClient.getLastLocation();
  String msg = "Current Location: " +
  Double.toString(currentLocation.getLatitude()) + "," +
  Double.toString(currentLocation.getLongitude());

  // Display the current location in the UI
  locationLabel.setText(msg);

  // To display the current address in the UI
  (new GetAddressTask(this)).execute(currentLocation);
 }
/*
 * Following is a subclass of AsyncTask which has been used to get
 * address corresponding to the given latitude & longitude.
 */
 private class GetAddressTask extends AsyncTask<Location, Void, String>{
  Context mContext;
  public GetAddressTask(Context context) {
     super();
     mContext = context;
  }

  /*
   * When the task finishes, onPostExecute() displays the address. 
   */
  @Override
  protected void onPostExecute(String address) {
     // Display the current address in the UI
     addressLabel.setText(address);
  }
  @Override
  protected String doInBackground(Location... params) {
     Geocoder geocoder =
     new Geocoder(mContext, Locale.getDefault());
     // Get the current location from the input parameter list
     Location loc = params[0];
     // Create a list to contain the result address
     List<Address> addresses = null;
     try {
        addresses = geocoder.getFromLocation(loc.getLatitude(),
        loc.getLongitude(), 1);
     } catch (IOException e1) {
        Log.e("LocationSampleActivity", 
        "IO Exception in getFromLocation()");
        e1.printStackTrace();
        return ("IO Exception trying to get address");
     } catch (IllegalArgumentException e2) {
        // Error message to post in the log
        String errorString = "Illegal arguments " +
        Double.toString(loc.getLatitude()) +
        " , " +
        Double.toString(loc.getLongitude()) +
        " passed to address service";
        Log.e("LocationSampleActivity", errorString);
        e2.printStackTrace();
        return errorString;
     }
     // If the reverse geocode returned an address
     if (addresses != null && addresses.size() > 0) {
        // Get the first address
        Address address = addresses.get(0);
        /*
        * Format the first line of address (if available),
        * city, and country name.
        */
        String addressText = String.format(
        "%s, %s, %s",
        // If there's a street address, add it
        address.getMaxAddressLineIndex() > 0 ?
        address.getAddressLine(0) : "",
        // Locality is usually a city
        address.getLocality(),
        // The country of the address
        address.getCountryName());
        // Return the text
        return addressText;
     } else {
        return "No address found";
     }
  }
}// AsyncTask class
}

参考链接http://www.tutorialspoint.com/android/android_location_based_services.htm