我目前正在尝试从当前位置找到最近的商店。我已经实现了不同的方法(即:排序),但无济于事,它只返回null。我花了很长时间才找出问题所在。每当我使用float distance = currPos.distanceTo(locationA);
时,它都会产生0.0
。经过进一步检查,我发现我的locationA
返回null。我尝试在2 for循环之前和之后访问marker.get(0).location
,而2 for循环之前的访问只返回一个值。
@Override
protected void onCreate(Bundle savedInstanceState) {
marker = new ArrayList();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
try {
jSonArray = (String) getIntent().getExtras().get("jsonArray");
jsonArray = new JSONArray(jSonArray);
for (int i = 0; i < jsonArray.length(); i++) {
branch = new Markers();
Float lat;
Float lon;
lat = Float.parseFloat(jsonArray.getJSONObject(i).getString("latitude"));
lon = Float.parseFloat(jsonArray.getJSONObject(i).getString("longitude"));
branch.location = new Location("");
branch.location.setLatitude(lat);
branch.location.setLongitude(lon);
marker.add(branch);
}
*marker.get(0).location is still accessible here*
for (int i = 0; i < marker.size(); i++) {
results[i] = distance(currPos.getLatitude(), currPos.getLongitude(), marker.get(i).location.getLatitude(), marker.get(i).location.getLongitude());
}
for (int i = 0; i < results.length; i++) {
if (results[i] < results[i + 1]) {
temp = marker.get(i).location;
}
}
*marker.get(0).location returns null here*
} catch (Exception ex) {
Log.d("Error", ex.toString());
}
}
以下是整个活动:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private static List<Markers> marker;
private static Markers branch;
private static Location temp;
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private static Location currPos;
private JSONArray jsonArray;
private double[] results;
private String jSonArray;
@Override
protected void onCreate(Bundle savedInstanceState) {
marker = new ArrayList();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
try {
jSonArray = (String) getIntent().getExtras().get("jsonArray");
jsonArray = new JSONArray(jSonArray);
for (int i = 0; i < jsonArray.length(); i++) {
branch = new Markers();
Float lat;
Float lon;
lat = Float.parseFloat(jsonArray.getJSONObject(i).getString("latitude"));
lon = Float.parseFloat(jsonArray.getJSONObject(i).getString("longitude"));
branch.location = new Location("");
branch.location.setLatitude(lat);
branch.location.setLongitude(lon);
marker.add(branch);
}
for (int i = 0; i < marker.size(); i++) {
results[i] = distance(currPos.getLatitude(), currPos.getLongitude(), marker.get(i).location.getLatitude(), marker.get(i).location.getLongitude());
}
for (int i = 0; i < results.length; i++) {
if (results[i] < results[i + 1]) {
temp = marker.get(i).location;
}
}
} catch (Exception ex) {
Log.d("Error", ex.toString());
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
private class Markers {
public Location location;
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
currPos = location;
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
public double distance(double lata, double longa, double latb, double longb) {
double d2r = Math.PI / 180;
double dlong = (longa - longb) * d2r;
double dlat = (lata - latb) * d2r;
double a = Math.pow(Math.sin(dlat / 2.0), 2) + Math.cos(latb * d2r)
* Math.cos(lata * d2r) * Math.pow(Math.sin(dlong / 2.0), 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double d = 6367 * c;
return d;
}
}