2017-02-05 14 views
0

私は場所の整理番号を持っています。私はリストをソートするこのメソッドを持っています。次に、リストの最初のlatとlongを変数に代入して、最も近いストアを取得します。私はそれの上にマーカーを置くためにnearest変数を使用する場合最も近い場所にはヌルが返されます

   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の値をチェックすると、座標が含まれていません。私は何かに欠けていますか?ここに私の全体の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

あなたの二つのスレッド間の競合状態があります。

mapFragment.getMapAsync(this); // thread 1 

fetchData(); // thread 2 

スレッド1人のニーズスレッド2が終了して動作するようにnearestを割り当てます。それ以外の場合は、

あなたはonPostExecuteの終わりにmapFragment.getMapAsync(MapsActivity.this);を呼び出すことができヌルですが、データがバックグラウンドタスクによってフェッチされていないので...

あなたAsynctaskは、現時点では無意味です。

関連する問題