通过标记绘制路径的问题

时间:2014-04-24 20:52:26

标签: android google-maps

在我的应用程序中,可以插入带触摸的标记,然后可以通过这些标记计算后续HTTP请求的路径。

问题在于,通常会跳过第一个标记,并在最后两个标记之间绘制一个的分段。

以下是代码:

public class MultipleTracksDrawer extends AbstractDrawer {

    private static final String TAG_LOG = MultipleTracksAsyncTask.class.getName();

    private boolean flag = false;

    void draw() {

        for(int i = 0; i < markers.size() - 1; i++) {

            Marker firstMarker = markers.get(i);
            Marker secondMarker = markers.get(i + 1);
            //I extract latitude and longitude from the markers
            LatLng firstLatLng = new LatLng(firstMarker.getPosition().latitude,      firstMarker.getPosition().longitude);
            LatLng secondLatLng = new LatLng(secondMarker.getPosition().latitude, secondMarker.getPosition().longitude);

            //Url for the request
            String URL = Utilities.getInstance().makeURL(firstLatLng.latitude, firstLatLng.longitude,
                secondLatLng.latitude, secondLatLng.longitude, travelMode);

            //At the end of the markers list i set the flag as true for draw the path
            if(i == markers.size() - 2) {
                flag = true;
            }

            MultipleTracksAsyncTask multipleTracksAsyncTask = new MultipleTracksAsyncTask(URL);
            multipleTracksAsyncTask.execute();
        }
    }

    private class MultipleTracksAsyncTask extends AsyncTask<Void,Void,String> {

        private ProgressDialog mDialog;
        private String URL;

        public MultipleTracksAsyncTask(String URL) {
            this.URL = URL;
        }

        protected void onPreExecute() {
            mDialog = ProgressDialog.show(context, "", "Loading...", true);
        }

        protected void onPostExecute(String result) {
            if(mDialog != null) {
                if(mDialog.isShowing()) {
                    mDialog.dismiss();
                }
            }

            if(result != null) {
                parseJSON(result);
                //I draw the path only if the flag is true
                if(flag) {
                    drawPath();
                }
            }
        }

        public String doInBackground(Void... param) {
            JSONRequest jParser = new JSONRequest();
            String json = jParser.getJSONFromUrl(URL,connectionTimeout,dataTimeout);
            return json;
        }
    }

    private void parseJSON(String result) {
        try {
            final JSONObject json = new JSONObject(result);
            //I get "routes" array
            JSONArray routeArray = json.getJSONArray("routes");
            JSONObject routes = routeArray.getJSONObject(0);
            JSONArray legsArray = routes.getJSONArray("legs");
            JSONObject legsObject = legsArray.getJSONObject(0);
            //I get distance and duration of the path
            JSONObject distance = legsObject.getJSONObject("distance");
            JSONObject duration = legsObject.getJSONObject("duration");
            JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
            String encodedString = overviewPolylines.getString("points");
            //Decoding
            model.getMarkersTrack().addAll(Utilities.getInstance().decodePoly(encodedString));

            mTrackDistance += distance.getInt("value");
            mTrackDuration += duration.getInt("value");
        }
        catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(context, "The path is not available", Toast.LENGTH_SHORT).show();
        }
    }

    private void drawPath() {

        for(int i = 0; i < model.getMarkersTrack().size() - 1; i++) {
            LatLng src = model.getMarkersTrack().get(i);
            LatLng dest = model.getMarkersTrack().get(i + 1);
            PolylineOptions polylineOptions = new PolylineOptions()
                .add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude,  dest.longitude))
                .width(5)
                .color(Color.BLUE).geodesic(true);
            Polyline polyline = googleMap.addPolyline(polylineOptions);
            //I save the polylines 
            model.getTrackPolylines().add(polyline);
        }
    }
}

我在这里也提到了HTTP请求的代码:

public class JSONRequest {

    private InputStream is = null;
    private String json = "";

    /**
     * Method that makes the HTTP request
     *
     * @param url URL of the HTTP request
     * @param connectionTimeout timeout for the connection
     * @param dataTimeout timeout for the download
     * @return
     */
    public String getJSONFromUrl(String url, int connectionTimeout, int dataTimeout) {

        try {
            HttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams,connectionTimeout);
            HttpConnectionParams.setSoTimeout(httpParams, dataTimeout);
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
            //GET request
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            //I get the response
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            //I read the response
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            json = sb.toString();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }
}

这是一张图片:http://imageshack.com/a/img835/504/m0fc.png

更新:

问题已解决!

现在我在MultipleTracksDrawer类的draw()方法中创建一个新的String URL,并将其提供给AsyncTask(作为输入参数)。这样就可以了。我编辑了代码。

0 个答案:

没有答案