【问题标题】:How to get current Location of user ?如何获取用户的当前位置?
【发布时间】:2014-03-12 04:40:14
【问题描述】:

我在android中做了一个应用程序。我必须找到用户的当前位置,即城市名称 我使用下面的代码,它可以生成纬度和经度,但没有得到城市的名称。

我的代码是:

public class GetCurrentLocation extends Activity implements OnClickListener {

private LocationManager locationMangaer=null;
private LocationListener locationListener=null; 

private Button btnGetLocation = null;
private EditText editLocation = null;   
private ProgressBar pb =null;

private static final String TAG = "Debug";
private Boolean flag = false;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //if you want to lock screen for always Portrait mode  
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    pb = (ProgressBar) findViewById(R.id.progressBar1);
    pb.setVisibility(View.INVISIBLE);

    editLocation = (EditText) findViewById(R.id.editTextLocation);  

    btnGetLocation = (Button) findViewById(R.id.btnLocation);
    btnGetLocation.setOnClickListener(this);

    locationMangaer = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

}

@Override
public void onClick(View v) {
    flag = displayGpsStatus();
    if (flag) {

        Log.v(TAG, "onClick");      

        editLocation.setText("Please!! move your device to see the changes in coordinates."+"\nWait..");

        pb.setVisibility(View.VISIBLE);
        locationListener = new MyLocationListener();

        locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10,
                locationListener);

        } else {
        alertbox("Gps Status!!", "Your GPS is: OFF");
    }

}

/*----------Method to Check GPS is enable or disable ------------- */
private Boolean displayGpsStatus() {
    ContentResolver contentResolver = getBaseContext().getContentResolver();
    boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(
            contentResolver, LocationManager.GPS_PROVIDER);
    if (gpsStatus) {
        return true;

    } else {
        return false;
    }
}

/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Your Device's GPS is Disable")
            .setCancelable(false)
            .setTitle("** Gps Status **")
            .setPositiveButton("Gps On",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // finish the current activity
                            // AlertBoxAdvance.this.finish();
                            Intent myIntent = new Intent(
                                    Settings.ACTION_SECURITY_SETTINGS);
                            startActivity(myIntent);
                            dialog.cancel();
                        }
                    })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // cancel the dialog box
                            dialog.cancel();
                        }
                    });
    AlertDialog alert = builder.create();
    alert.show();
}

/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
    @Override
    public void onLocationChanged(Location loc) {

            editLocation.setText("");
            pb.setVisibility(View.INVISIBLE);
            Toast.makeText(getBaseContext(),"Location changed : Lat: " + loc.getLatitude()
                            + " Lng: " + loc.getLongitude(),Toast.LENGTH_SHORT).show();
            String longitude = "Longitude: " +loc.getLongitude();  
            Log.v(TAG, longitude);
            String latitude = "Latitude: " +loc.getLatitude();
            Log.v(TAG, latitude);

            /*----------to get City-Name from coordinates ------------- */
            String cityName=null;                 
            Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());                  
            List<Address>  addresses;  
            try {  
             addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);  
             if (addresses.size() > 0)  
              System.out.println(addresses.get(0).getLocality());  
             cityName=addresses.get(0).getLocality();  
            } catch (IOException e) {                 
             e.printStackTrace();  
            } 

            String s = longitude+"\n"+latitude +"\n\nMy Currrent City is: "+cityName;
            editLocation.setText(s);

    }


    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub          
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub          
    }


    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }
      }
}

如何获取城市名称,即用户的当前位置(如德里、孟买等)?

【问题讨论】:

  • 你访问的方式不对,请访问我的这个answer

标签: android geolocation google-geocoder


【解决方案1】:

试试这个方法:

List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);

if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
strReturnedAddress.append(returnedAddress.getLocality()).append("\n");
strReturnedAddress.append(areturnedAddress.getPostalCode()).append("\n");
strReturnedAddress.append(returnedAddress.getCountryName()).append("\n");

}
myAddress.setText(strReturnedAddress.toString());

欲了解更多信息,请访问:http://developer.android.com/reference/android/location/Geocoder.html

【讨论】:

  • 我使用了这两个代码,但它们都不起作用。单击按钮后,它会处理很长时间并且不显示任何结果
  • @user3405932 为什么不呢?这段代码在我的情况下运行完美。
  • 我在模拟器的 API 19 上使用它
  • @user3405932 测试到真实物理设备并返回。请
  • 哎呀......仍然在真实设备上加载并且没有结果......你能给我完整的代码吗?
【解决方案2】:

试试这个-

Geocoder geocoder = new Geocoder(getActivity(),Locale.ENGLISH);
            StringBuilder stringBuilder = new StringBuilder();
            List<Address> addressList;
            try {
                addressList = geocoder.getFromLocation(Latitude, Longitude, 1);

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

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

不要忘记在清单中授予权限-

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

【讨论】:

  • 在邮政编码和地区中,您将获得城市名称和州名。
【解决方案3】:

我建议使用 google play 服务来检查位置 http://developer.android.com/google/play-services/location.html

如果您的应用可以安装在没有 google play 服务的设备上,请查看此代码 https://github.com/BeyondAR/beyondar/tree/master/android/BeyondAR_Framework/src/com/beyondar/android/util/location 并从位置管理器开始

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-20
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多