0

Googleマップを使用していくつかのマーカーを表示しています。マーカーはデータベースからダウンロードされ、同時に、ユーザーの現在の位置とデータベースから取得したマーカーの間の距離行列を Google API から取得します。

私の問題は、私が .get でこれを行っていて、UI をブロックしていたことです (.get が ui をブロックしていることを読みました:

dataFromAsyncTask = testAsyncTask.get();

今、私はUIをブロックせずに同じことをしようとしていますが、同時に、または良い意味で、このマーカーの距離を取得することはできません.

助けていただければ幸いです。

これは、古い間違った .get を使用した私のコードです。

 for (City city : listCity.getData()) {
        geoPoint = city.getLocation();
    nameBeach = city.getName();

    if (geoPoint == null) {

    } else {
        latitude = String.valueOf(geoPoint.getLatitude());
        longitude = String.valueOf(geoPoint.getLongitude());

        startRetrievenDistanceAndDuration();

        try {
            dataFromAsyncTask = testAsyncTask.get();
        } catch (InterruptedException i) {

        } catch (ExecutionException e) {
        }

        mMap.addMarker(new MarkerOptions().position(new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()))
                .title(nameCity)
                .snippet(dataFromAsyncTask)
                .icon(BitmapDescriptorFactory.defaultMarker()));
    }
}

startRetrievenDistanceAndDuration メソッド:

private void startRetrievenDistanceAndDuration() {
final String url;

testAsyncTask = new DistanceBetweenLocations(new FragmentCallback() {

    @Override
    public void onTaskDone(String result) {

    }
});
url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentLatitude + "," + currentlongitude + "&destinations=" + latitude + "," + longitude + "&key=xxx";
testAsyncTask.execute(new String[]{url});
}
public interface FragmentCallback {
    public void onTaskDone(String result);

AsyncTask クラス:

        @Override
        protected String doInBackground(String... params) {
            HttpURLConnection urlConnection = null;
            URL url = null;
            StringBuilder result = null;
            String duration = "";
            String distance = "";

            try {
                url=new URL(params[0]);
            }catch (MalformedURLException m){

            }
            try {
                urlConnection = (HttpURLConnection) url.openConnection();
            }catch (IOException e){}

            try {
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                result = new StringBuilder();
                String line;
                while((line = reader.readLine()) != null) {
                    result.append(line);
                }
            }catch (IOException e){

            } finally {
                urlConnection.disconnect();
            }

            try {
                JSONObject jsonObject = new JSONObject(result.toString());
                JSONArray jsonArray = jsonObject.getJSONArray("rows");
                JSONObject object_rows = jsonArray.getJSONObject(0);
                JSONArray jsonArrayElements = object_rows.getJSONArray("elements");
                JSONObject  object_elements = jsonArrayElements.getJSONObject(0);
                JSONObject object_duration = object_elements.getJSONObject("duration");
                JSONObject object_distance = object_elements.getJSONObject("distance");

                duration = object_duration.getString("text");
                distance = object_distance.getString("text");

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return distance + ", " + duration;

        }

        @Override
        protected void onPostExecute(String result) {
            mFragmentCallback.onTaskDone(result);
        }
}

私はこれをやろうとしていますが、リストの最後のマーカーのみを表示しています:

ループ内で次のメソッドを呼び出します。

startRetrievenDistanceAndDuration();

そして onTaskDone でマーカーを配置しようとしますが、リストの最後のマーカーのみを取得します

@Override
            public void onTaskDone(String result) {
                mMap.addMarker(new MarkerOptions().position(new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()))
                        .title(nameBeach)
                        .snippet(result)
                        .icon(BitmapDescriptorFactory.defaultMarker()));

            }

変更後の更新: (まだ動作しません) Asynctask でデータを解析して onPostExecute で送信できますが、取得できる値は 1 つだけで、9 つの値は取得できません....

主な活動:

DistanceBetweenLocations task = new DistanceBetweenLocations(mlatituDouble, mlongitudeDouble){
                    @Override
                    protected void onPostExecute(HashMap<String, String> result) {
                        super.onPostExecute(result);

                        String name = result.get("beachName");
                        String distance = result.get("distance");
                        String duration = result.get("duration");
                        String latitue = result.get("latitude");
                        String longitude = result.get("longitude");

                        Double mlatituDouble = Double.parseDouble(latitue);
                        Double mlongitudeDouble = Double.parseDouble(longitude);


                        if (mMap == null) {

                            mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.mapView))
                                    .getMap();

                                Toast.makeText(getActivity(), "mMap NO null", Toast.LENGTH_SHORT).show();
                                mMap.addMarker(new MarkerOptions().position(new LatLng(mlatituDouble, mlongitudeDouble))
                                        .title(name)
                                        .snippet(distance + " " + duration)
                                        .icon(BitmapDescriptorFactory.defaultMarker()));
                        }
                    }
                };

                task.execute();

非同期タスク クラス:。

public class DistanceBetweenLocations extends AsyncTask<String, String, HashMap<String, String>> {

    Double currentLatitude;
    Double currentlongitude;
    public BeachMap beachMap;
    public BackendlessCollection<Beach> dataBeach;
    public GoogleMap mMap;
    String latitude;
    String longitude;
    HashMap<String, String> map;

    public DistanceBetweenLocations(Double currentLatitude, Double currentlongitude){
        this.currentLatitude = currentLatitude;
        this.currentlongitude = currentlongitude;
    }

    @Override
    protected HashMap<String, String> doInBackground(String... params) {

        dataBeach = beachMap.listBeach;

        for (Beach city : dataBeach.getData()) {
            GeoPoint geoPoint = city.getLocation();
            String nameBeach = city.getName();

            if (geoPoint == null) {

            } else {
                latitude = String.valueOf(geoPoint.getLatitude());
                longitude = String.valueOf(geoPoint.getLongitude());

                HttpURLConnection urlConnection = null;
                URL url = null;
                StringBuilder result = null;
                String duration = "";
                String distance = "";

                try {
                    url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentLatitude + "," + currentlongitude + "&destinations=" + latitude + "," + longitude + "&key=xxxx");
                } catch (MalformedURLException m) {

                }
                try {
                    urlConnection = (HttpURLConnection) url.openConnection();
                } catch (IOException e) {
                }

                try {
                    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    result = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }
                } catch (IOException e) {

                } finally {
                    urlConnection.disconnect();
                }

                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    JSONArray jsonArray = jsonObject.getJSONArray("rows");
                    JSONObject object_rows = jsonArray.getJSONObject(0);
                    JSONArray jsonArrayElements = object_rows.getJSONArray("elements");
                    JSONObject object_elements = jsonArrayElements.getJSONObject(0);
                    JSONObject object_duration = object_elements.getJSONObject("duration");
                    JSONObject object_distance = object_elements.getJSONObject("distance");

                    duration = object_duration.getString("text");
                    distance = object_distance.getString("text");


                    map = new HashMap<String, String>();
                    map.put("beachName", nameBeach);
                    map.put("distance", distance);
                    map.put("duration", duration);
                    map.put("latitude", latitude);
                    map.put("longitude", longitude);


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return map;
    }

}
4

2 に答える 2

0

あなたが何をしようとしているのか正確にはわかりませんが、これを必要以上に複雑にしたと思います。

私が理解していることから、オブジェクトのリストがあり、それらを使用していくつかの URL を作成し、そこからオブジェクトを作成するために使用するオブジェクトをCity取得します。JSONMarkerOptions

次のように使用してそれを行うことができますAsyncTask

public class Task extends AsyncTask<City, Void, Markers> {

    String currentLatitude;
    String currentlongitude;

    public Task(String currentLatitude, String currentlongitude){
        this.currentLatitude = currentLatitude;
        this.currentlongitude = currentlongitude;
    }

    @Override
    protected String doInBackground(City... cities) {
        final Markers mMap = ...;
        for (City city : cities) {
            GeoPoint geoPoint = city.getLocation();
            String nameBeach = city.getName();

            if (geoPoint != null) {
                String latitude = String.valueOf(geoPoint.getLatitude());
                String longitude = String.valueOf(geoPoint.getLongitude());

                HttpURLConnection urlConnection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentLatitude + "," + currentlongitude + "&destinations=" + latitude + "," + longitude + "&key=xxx";);
                    urlConnection = (HttpURLConnection) url.openConnection();
                    reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    StringBuilder result = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }
                    JSONObject jsonObject = new JSONObject(result.toString()).getJSONArray("rows").getJSONObject(0).getJSONArray("elements").getJSONObject(0);
                    String duration = jsonObject.getJSONObject("duration").getString("text");
                    String distance = jsonObject.getJSONObject("distance").getString("text");

                    mMap.addMarker(new MarkerOptions().position(new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()))
                            .title(nameBeach)
                            .snippet(distance + ", " + duration)
                            .icon(BitmapDescriptorFactory.defaultMarker()));
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if(reader!=null){
                        try {
                            reader.close();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                    if (urlConnection != null) {
                        try {
                            urlConnection.disconnect();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

        return mMap;
    }
}

そして、このタスクを使用する方法は次のとおりです。

public class Login extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(...);
        Task task = new Task(currentLatitude, currentlongitude){
            @Override
            protected void onPostExecute(Markers markers) {
                super.onPostExecute(markers);
                //This runs on the UI thread and "markers" is the "mMap" object that was create on the background thread.
            }
        };
        List<City> cities = ....
        task.execute(cities.toArray(new City[cities.size()]));
    }
}

AsyncTaskのメソッドで長時間実行されるすべての操作を実行する必要があるという考えです doInBackground(...)。また、応答を処理するために他のオブジェクトを作成する必要はありません。タスクを作成したクラス内のAsyncTaskタスクをオーバーライドできます。onPostExecute(...)

于 2016-05-31T23:19:27.323 に答える