如何使用Google Maps API跟踪路径,就像正在运行的应用一样?

时间:2016-02-27 10:28:54

标签: android json google-maps

我正在尝试像正在运行的应用程序一样实现路径跟踪。用户加载应用程序并单击按钮后,会话将开始记录位置更新。我正在使用记录位置 if (myPositions == null) { myPositions = new JSONArray(); } JSONObject myPosition = new JSONObject(); try { myPosition.put("lat",currentLatitude); myPosition.put("long",currentLongitude); } catch (JSONException e) { e.printStackTrace(); } myPositions.put(myPosition); 。我使用JSON数组和对象保存数据。

for (int i=0; i < myPositions.length(); i++) {
            JSONObject obj = myPositions.getJSONObject(i);
            long latitude = obj.getLong("lat");
            long longitude = obj.getLong("long");

我正在通过

检索
int permissionCheck = ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE);

        int permissionCheck1 = ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);

        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                1000);

        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                2000);

        Toast.makeText(this, permissionCheck1 + " Permission " + permissionCheck, Toast.LENGTH_LONG).show();

现在我如何使用这些值来追踪用户所涵盖的路径?

我知道我可以使用谷歌地图道路api和折线来追踪路径。使用道路api的折线将被卡在路上,因此我可以实现我的目标。但是,使用javascript和http urls的道路api文档,我不知道如何实现。有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

我使用谷歌地图道路api,它使用坐标向服务器发送http请求,返回的结果是另一组坐标,对应于道路。然后我通过绘制折线来追踪它。

            stringUrl = "https://roads.googleapis.com/v1/snapToRoads?path=" + old_latitude + ","
                + old_longitude + "|" + currentLatitude + "," + currentLongitude +
                "&interpolate=true&key=" + key;
        ConnectivityManager connMgr = (ConnectivityManager)
                getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnected()) {
            new WebTask().execute(stringUrl);
        } else {
            Toast.makeText(getActivity(), "No network connection available.", Toast.LENGTH_LONG);
        }

上面的代码使用Webtask()函数发送http请求。我使用了谷歌开发者页面,它的示例代码。

 private class WebTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        // params comes from the execute() call: params[0] is the url.
        try {
            return downloadUrl(urls[0]);
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }

    private String downloadUrl(String url) throws IOException {

        InputStream is = null;


        try {
            URL urlx = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) urlx.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            // Starts the query
            conn.connect();
            int response = conn.getResponseCode();
            Log.d("flip", "The response is: " + response);
            is = conn.getInputStream();
            //  Log.d("flip is", String.valueOf(is));
            // Convert the InputStream into a string
            String contentAsString = readIt(is);
            Log.d("flip content", contentAsString);
            return contentAsString;


            // Makes sure that the InputStream is closed after the app is
            // finished using it.
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    private String readIt(InputStream stream) throws IOException {

        // Reader reader = new InputStreamReader(stream, "UTF-8");
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        StringBuilder stringBuilder = new StringBuilder();
        String ch;
        while((ch = streamReader.readLine())!=null)
        {
            stringBuilder.append(ch);
        }
        return stringBuilder.toString();
    }

    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {

        Log.d("flip", result);

        double old_lat = 0, old_long = 0;

        try {

            JSONObject mainObj = new JSONObject(result);
            JSONArray jsonarray =mainObj.getJSONArray("snappedPoints");

            for (int i = 0; i < jsonarray.length(); i++)

            {
                JSONObject arrayElem = jsonarray.getJSONObject(i);
                JSONObject locationa = arrayElem.getJSONObject("location");
                double lati = locationa.getDouble("latitude"); //save it somewhere
                double longi = locationa.getDouble("longitude"); //save it somewhere
                Log.d("flip lat", String.valueOf(lati));
                Log.d("flip long", String.valueOf(longi));

                if (old_lat != 0 && old_long != 0) {
                    Polyline line = mMap.addPolyline(new PolylineOptions()
                            .add(new LatLng(old_lat, old_long), new LatLng(lati, longi))
                            .width(10));
                }
                old_lat = lati;
                old_long = longi;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}

那就是它!那也是它的情节!