Java 在Android中显示州名称以及纬度和经度
最初,我使用以下代码在应用程序中显示当前纬度和经度:Java 在Android中显示州名称以及纬度和经度,java,android,google-maps,geolocation,Java,Android,Google Maps,Geolocation,最初,我使用以下代码在应用程序中显示当前纬度和经度: package com.coders.location; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Lo
package com.coders.location;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient mFusedLocationClient;
private double wayLatitude = 0.0, wayLongitude = 0.0;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
private android.widget.Button btnLocation;
private TextView txtLocation;
private android.widget.Button btnContinueLocation;
private TextView txtContinueLocation;
private StringBuilder stringBuilder;
private boolean isContinue = false;
private boolean isGPS = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.txtContinueLocation = (TextView) findViewById(R.id.txtContinueLocation);
this.btnContinueLocation = (Button) findViewById(R.id.btnContinueLocation);
this.txtLocation = (TextView) findViewById(R.id.txtLocation);
this.btnLocation = (Button) findViewById(R.id.btnLocation);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10 * 1000); // 10 seconds
locationRequest.setFastestInterval(5 * 1000); // 5 seconds
new GpsUtils(this).turnGPSOn(new GpsUtils.onGpsListener() {
@Override
public void gpsStatus(boolean isGPSEnable) {
// turn on GPS
isGPS = isGPSEnable;
}
});
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
*******************************************************
for (Location location : locationResult.getLocations()) {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
if (!isContinue) {
txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
} else {
stringBuilder.append(wayLatitude);
stringBuilder.append("-");
stringBuilder.append(wayLongitude);
stringBuilder.append("\n\n");
txtContinueLocation.setText(stringBuilder.toString());
}
*******************************************************
if (!isContinue && mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(locationCallback);
}
}
}
}
};
btnLocation.setOnClickListener(v -> {
if (!isGPS) {
Toast.makeText(this, "Please turn on GPS", Toast.LENGTH_SHORT).show();
return;
}
isContinue = false;
getLocation();
});
btnContinueLocation.setOnClickListener(v -> {
if (!isGPS) {
Toast.makeText(this, "Please turn on GPS", Toast.LENGTH_SHORT).show();
return;
}
isContinue = true;
stringBuilder = new StringBuilder();
getLocation();
});
}
private void getLocation() {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
AppConstants.LOCATION_REQUEST);
} else {
if (isContinue) {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
} else {
mFusedLocationClient.getLastLocation().addOnSuccessListener(MainActivity.this, location -> {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
} else {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
});
}
}
}
@SuppressLint("MissingPermission")
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1000: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (isContinue) {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
} else {
mFusedLocationClient.getLastLocation().addOnSuccessListener(MainActivity.this, location -> {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
} else {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
});
}
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == AppConstants.GPS_REQUEST) {
isGPS = true; // flag maintain before get location
}
}
}
}
当我这样做时,代码运行良好。然后,我尝试更新代码,因为我需要显示当前位置的状态“即显示用户手机当前所在的状态(例如南卡罗来纳州、马萨诸塞州、加利福尼亚州等)
这是更新的代码:
package com.coders.location;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient mFusedLocationClient;
private double wayLatitude = 0.0, wayLongitude = 0.0;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
private android.widget.Button btnLocation;
private TextView txtLocation;
private android.widget.Button btnContinueLocation;
private TextView txtContinueLocation;
private StringBuilder stringBuilder;
private boolean isContinue = false;
private boolean isGPS = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.txtContinueLocation = (TextView) findViewById(R.id.txtContinueLocation);
this.btnContinueLocation = (Button) findViewById(R.id.btnContinueLocation);
this.txtLocation = (TextView) findViewById(R.id.txtLocation);
this.btnLocation = (Button) findViewById(R.id.btnLocation);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10 * 1000); // 10 seconds
locationRequest.setFastestInterval(5 * 1000); // 5 seconds
new GpsUtils(this).turnGPSOn(new GpsUtils.onGpsListener() {
@Override
public void gpsStatus(boolean isGPSEnable) {
// turn on GPS
isGPS = isGPSEnable;
}
});
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
*******************************************************
for (Location location : locationResult.getLocations()) {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
Address address = addresses.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());
}
} catch (IOException e){
}
if (!isContinue) {
txtLocation.setText(stringBuilder.toString());
} else {
stringBuilder.append(wayLatitude);
stringBuilder.append("-");
stringBuilder.append(wayLongitude);
stringBuilder.append("\n\n");
txtContinueLocation.setText(stringBuilder.toString());
}
*******************************************************
if (!isContinue && mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(locationCallback);
}
}
}
}
};
btnLocation.setOnClickListener(v -> {
if (!isGPS) {
Toast.makeText(this, "Please turn on GPS", Toast.LENGTH_SHORT).show();
return;
}
isContinue = false;
getLocation();
});
btnContinueLocation.setOnClickListener(v -> {
if (!isGPS) {
Toast.makeText(this, "Please turn on GPS", Toast.LENGTH_SHORT).show();
return;
}
isContinue = true;
stringBuilder = new StringBuilder();
getLocation();
});
}
private void getLocation() {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
AppConstants.LOCATION_REQUEST);
} else {
if (isContinue) {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
} else {
mFusedLocationClient.getLastLocation().addOnSuccessListener(MainActivity.this, location -> {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
} else {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
});
}
}
}
@SuppressLint("MissingPermission")
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1000: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (isContinue) {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
} else {
mFusedLocationClient.getLastLocation().addOnSuccessListener(MainActivity.this, location -> {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
} else {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
});
}
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == AppConstants.GPS_REQUEST) {
isGPS = true; // flag maintain before get location
}
}
}
}
package com.coders.location;
导入android.Manifest;
导入android.annotation.SuppressLint;
导入android.app.Activity;
导入android.content.Intent;
导入android.content.pm.PackageManager;
导入android.location.Address;
导入android.location.Geocoder;
导入android.location.location;
导入android.os.Bundle;
导入android.support.annotation.NonNull;
导入android.support.v4.app.ActivityCompat;
导入android.support.v7.app.AppActivity;
导入android.widget.Button;
导入android.widget.TextView;
导入android.widget.Toast;
导入com.google.android.gms.location.FusedLocationProviderClient;
导入com.google.android.gms.location.LocationCallback;
导入com.google.android.gms.location.LocationRequest;
导入com.google.android.gms.location.LocationResult;
导入com.google.android.gms.location.LocationServices;
导入java.io.IOException;
导入java.util.List;
导入java.util.Locale;
公共类MainActivity扩展了AppCompatActivity{
私有FusedLocationProviderClient mFusedLocationClient;
私人双路纬度=0.0,路经度=0.0;
私人位置请求位置请求;
私有位置回调LocationCallback;
私有android.widget.Button btnLocation;
私有文本视图txtLocation;
私有android.widget.Button btnConcontinueLocation;
私有文本视图txtContinueLocation;
私人StringBuilder StringBuilder;
私有布尔值isContinue=false;
私有布尔值isGPS=false;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.txtContinueLocation=(TextView)findViewById(R.id.txtContinueLocation);
this.btnConcontinueLocation=(按钮)findViewById(R.id.btnConcontinueLocation);
this.txtLocation=(TextView)findViewById(R.id.txtLocation);
this.btnLocation=(按钮)findViewById(R.id.btnLocation);
mFusedLocationClient=LocationServices.getFusedLocationProviderClient(此);
locationRequest=locationRequest.create();
locationRequest.setPriority(locationRequest.PRIORITY\u高精度);
locationRequest.setInterval(10*1000);//10秒
locationRequest.SetFastTestInterval(5*1000);//5秒
new-GpsUtils(this.turnGPSOn)(new-GpsUtils.onGpsListener(){
@凌驾
public void gpsStatus(布尔值isGPSEnable){
//打开GPS
isGPS=isGPSEnable;
}
});
locationCallback=新locationCallback(){
@凌驾
public void onLocationResult(LocationResult LocationResult){
if(locationResult==null){
返回;
}
*******************************************************
对于(位置:locationResult.getLocations()){
如果(位置!=null){
wayLatitude=location.getLatitude();
wayLongitude=location.getLongitude();
双纬度=location.getLatitude();
double longitude=location.getLongitude();
Geocoder gc=新的地理编码器(getApplicationContext(),Locale.getDefault());
试一试{
列表地址=gc.getFromLocation(纬度,经度,1);
如果(地址.size()>0){
地址=地址。获取(0);
对于(int i=0;i{
如果(!isGPS){
Toast.makeText(这个“请打开GPS”,Toast.LENGTH_SHORT.show();
返回;
}
isContinue=false;
getLocation();
});
btnContinueLocation.setOnClickListener(v->{
如果(!isGPS){
Toast.makeText(这个“请打开GPS”,Toast.LENGTH_SHORT.show();
返回;
}
isContinue=true;
stringBuilder=新的stringBuilder();
public static final String GOOGLE_ETA = "https://maps.googleapis.com/maps/";
public static Retrofit getEtaClient() {
if (retrofitEtaGoogle == null) {
retrofitEtaGoogle = new Retrofit.Builder()
.baseUrl(GOOGLE_ETA)
.client(provideOkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofitEtaGoogle;
}
@GET("api/geocode/json?key="+ Consts.GOOGLE_API_KEY)
Call<GoogleGeoCodeApiResponseModel> getPlaceFromLatLng(@Query("latlng") String latLng);
String latLng = location.getLatitude() + "," + location.getLongitude();
ApiInterface apiInterface = RetrofitClient.getEtaClient().create(ApiInterface.class);
Call<GoogleGeoCodeApiResponseModel> call = apiInterface.getPlaceFromLatLng(latLng);
call.enqueue(new Callback<GoogleGeoCodeApiResponseModel>() {
@Override
public void onResponse(Call<GoogleGeoCodeApiResponseModel> call, Response<GoogleGeoCodeApiResponseModel> response) {
if (response.body().getStatus() != null && response.body().getStatus().equals("OK")) {
addressObj = new GoogleAddressLocalModel();
addressObj.setName(response.body().getResults().get(0).getFormattedAddress());
addressObj.setLat(response.body().getResults().get(0).getGeometry().getLocation().getLat());
addressObj.setLng(response.body().getResults().get(0).getGeometry().getLocation().getLng());
for (GoogleGeoCodeApiResponseModel.AddressComponent obj : response.body().getResults().get(0).getAddressComponents()) {
for (String type : obj.getTypes()) {
if (type.contains("postal_code")) {
addressObj.setPostalCode(obj.getLongName());
} else if (type.contains("country")) {
addressObj.setCountryId(obj.getShortName());
addressObj.setCountryName(obj.getLongName());
} else if (type.contains("administrative_area_level_2")) {
addressObj.setCityName(obj.getLongName());
}
}
}
} else if (response.body().getStatus() != null) {
Log.e("ErrroGettingAddress", response.body().getStatus());
}
}
@Override
public void onFailure(Call<GoogleGeoCodeApiResponseModel> call, Throwable t) {
Log.e("ErrroGettingAddress", t.getLocalizedMessage());
}
});
}
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Check if GPS is enabled or not.
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
Here is the sample code to do so
@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 Current City is: "
+ cityName;
editLocation.setText(s);
}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}