【问题标题】:How do I trace a path using Google Maps API, just like a running app?如何使用 Google Maps API 跟踪路径,就像正在运行的应用程序一样?
【发布时间】:2016-02-27 10:28:54
【问题描述】:

我正在尝试像正在运行的应用程序一样实现路径跟踪。一旦我的用户加载应用程序并单击按钮,会话就会开始记录位置更新。我正在使用 LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient)。我正在使用 JSON 数组和对象保存数据。

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

我正在检索

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

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

我知道我可以使用谷歌地图道路 API 和折线来追踪路径。折线,使用道路 api,被捕捉到道路,因此我可以实现我的目标。但是,使用javascript和http url的roads api文档,我不知道如何实现。有人可以帮帮我吗?

【问题讨论】:

  • 我很好奇您使用什么 IDE 来开发应用程序?
  • Windows 10 上的 Android Studio

标签: android json google-maps


【解决方案1】:

我使用了google maps road 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();
        }

    }
}

就是这样!这也是情节!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多