2017-02-05 4 views
0

店舗の枝の異なる緯度と経度を含むJSON配列を取得しました。私は、リスト内でそれを置く:現在の場所から最も近いマーカーを取得します(Android、Googleマップ)

 @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); 
       } 

      } catch (Exception ex) { 
       Log.d("Error", ex.toString()); 
      } 
     } 

これは私のMarkersクラスです:

private class Markers { 
    public float latitude; 
    public float longitude; 
} 

今、私は私の現在の場所をGoogleマップのAPI V2を使用して座標取得することができる午前:

LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); 
    MarkerOptions markerOptions = new MarkerOptions(); 
    markerOptions.position(latLng); 
    markerOptions.title("Current Location"); 
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)); 
    mCurrLocationMarker = mMap.addMarker(markerOptions); 

今私は不思議です、私は私の現在の場所から最も近い店の支店を取得し、それにマーカーを配置する方法私は店の支店の場所と私の現在の場所の私のリストがありますか?私は見た実装を理解していないので、誰かが私にこれを達成する方法を教えれば大きな助けになるでしょう。乾杯!

答えて

0

一つの方法は、あなたのマーカーをソートし、ソートされた配列の最初の要素を使用することです:

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 = location.distanceTo(locationA); 
     float distanceTwo = location.distanceTo(locationB); 
     return Float.compare(distanceOne, distanceTwo); 
    } 
} 

は、次に、あなたの現在の場所までの距離に基づいて、あなたのマーカーをソートしています。 その後、marker-Arrayの最初の要素を使用してmMapインスタンスに追加します。

+0

私はforPostExecuteメソッドのforループの後にこれを置いていますか?私はこれについて約1時間作業していますが、それでもまだヌル値を返しています... – Paradigm

+0

あなたのfor-each stuff後、yes。あなたはどこでヌル値を得ますか? – Boni2k

+0

問題はソート自体ではありませんでした...私の位置リストには、判明したとおりにヌル値が入ります。しかし、答えをありがとう。興味があれば、私の他の質問です:[link](http://stackoverflow.com/questions/42055198/arraylist-element-suddenly-becomes-null) – Paradigm

関連する問題