我有位置marker
的arraylist。我有这种方法来排序列表。然后我将列表中的第一个lat和long分配给一个变量,这样我就可以得到最近的商店。
Collections.sort(marker, new Comparator<Markers>() {
@Override
public int compare(Markers a, Markers b) {
Location locationA = new Location("point A");
locationA.setLatitude(a.latitude);
locationA.setLongitude(a.longitude);
Location locationB = new Location("point B");
locationB.setLatitude(b.latitude);
locationB.setLongitude(b.longitude);
float distanceOne = currPos.distanceTo(locationA);
float distanceTwo = currPos.distanceTo(locationB);
return Float.compare(distanceOne, distanceTwo);
}
});
nearest = new LatLng(marker.get(0).latitude, marker.get(0).longitude);
但是,当我使用nearest
变量在其上放置标记时,地图上没有贴出任何标记。当我检查nearest
的值时,它不包含任何坐标。我错过了什么吗?这是我的整个MapsActivity.java
:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private static LatLng nearest;
private static Location currPos;
@Override
protected void onCreate(Bundle savedInstanceState) {
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);
fetchData();
}
@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);
mMap.addMarker(new MarkerOptions()
.position(new LatLng(nearest.latitude,nearest.longitude))
.title("Nearest Store"));
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
public void fetchData() {
new AsyncTask() {
private List<Markers> marker;
private JSONArray jsonArray;
@Override
protected void onPreExecute() {
super.onPreExecute();
marker = new ArrayList();
}
@Override
protected Object doInBackground(Object[] objects) {
return null;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
try {
Intent mapsIntent = getIntent();
String jSonArray = mapsIntent.getStringExtra("jsonArray");
jsonArray = new JSONArray(jSonArray);
for(int i = 0; i < jsonArray.length(); i++) {
Markers branch = new Markers();
branch.latitude = Float.parseFloat(jsonArray.getJSONObject(i).getString("latitude"));
branch.longitude = Float.parseFloat(jsonArray.getJSONObject(i).getString("longitude"));
marker.add(branch);
}
Collections.sort(marker, new Comparator<Markers>() {
@Override
public int compare(Markers a, Markers b) {
Location locationA = new Location("point A");
locationA.setLatitude(a.latitude);
locationA.setLongitude(a.longitude);
Location locationB = new Location("point B");
locationB.setLatitude(b.latitude);
locationB.setLongitude(b.longitude);
float distanceOne = currPos.distanceTo(locationA);
float distanceTwo = currPos.distanceTo(locationB);
return Float.compare(distanceOne, distanceTwo);
}
});
nearest = new LatLng(marker.get(0).latitude, marker.get(0).longitude);
} catch (Exception ex) {
Log.d("Error", ex.toString());
}
}
}.execute();
}
private class Markers {
public float latitude;
public float longitude;
}
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();
}
//Place current location marker
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;
}
}
}
}
答案 0 :(得分:0)
你的两个线程之间存在竞争条件。
mapFragment.getMapAsync(this); // thread 1
fetchData(); // thread 2
线程1需要线程2完成并指定nearest
才能工作。否则为空
您可以在onPostExecute结束时调用mapFragment.getMapAsync(MapsActivity.this);
,但是......
您的Asynctask目前毫无意义,因为后台任务不会获取任何数据。