[英]Display Name of the State along with Latitude and Longitude in Android
最初,我使用以下代碼在應用程序中顯示當前的緯度和經度:
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
}
}
}
}
當我這樣做時,代碼運行良好。 然后我嘗試更新代碼,因為我需要顯示當前位置的 State 以及“即在用戶電話當前所在的位置(例如南卡羅來納州、馬薩諸塞州、加利福尼亞州等)顯示 state。
這是更新的代碼:
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
}
}
}
}
這段代碼現在甚至不顯示當前的緯度和經度。 有人可以幫我弄這個嗎。 我正在尋找顯示 State 以及當前位置的緯度和經度。
已實施更改並且似乎與我的問題最相關的代碼行在代碼的開頭和結尾處用一長串星號標記,如下所示:********** ************************************************
我們需要做的就是在清單文件中添加這個權限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
並像這樣創建一個 LocationManager 實例:
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Check if GPS is enabled or not.
然后實現 LocationListener 並獲取坐標:
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
Here is the sample code to do so
私人 class MyLocationListener 實現 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 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) {}
}
請參閱此流程: 如何在 Android 中以編程方式獲取當前 GPS 位置?
實際上這段代碼現在不起作用。 Google 已棄用上述代碼,現在您需要使用以下代碼。
我用的是 Retrofit Retrofit 客戶端
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;
}
Api接口class
@GET("api/geocode/json?key="+ Consts.GOOGLE_API_KEY)
Call<GoogleGeoCodeApiResponseModel> getPlaceFromLatLng(@Query("latlng") String latLng);
在 updateLocationUI() 方法中
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());
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.