两个位置之间不显示折线,但显示时间和距离

2024-02-16

注意:抱歉我的英语不好,因为英语不是我的母语,我为此使用了谷歌翻译。

我正在开发一个 Android 地图应用程序,用户可以在其中找到朋友的当前位置。为了存储当前位置,我使用 Firebase 实时数据库。在 Lalit Singh 之前的帮助下,它现在可以显示时间和距离,但仍然没有更新两个不同地点之间的折线。我的更新代码如下。

mapsActivity.java(我从火力基地获取朋友位置并调用更新的时间、距离和折线方法)

  public void proceed(final View view) {

    DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Email");

    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                UserInformation details = dataSnapshot1.getValue(UserInformation.class);

                if (mMap != null) {
                    mMap.clear();
                }

                MarkerOptions markerOptions = new MarkerOptions();
                LatLng latLng1 = new LatLng(details.getLatitude(), details.getLongitude());
                markerOptions.position(latLng1);
                markerOptions.title(String.valueOf(latLng1));
                mMap.addMarker(markerOptions).setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng1));
                mMap.animateCamera(CameraUpdateFactory.zoomTo(14));

                distance_task.getDirectionsUrl(latLng1, markerOptions.getPosition());
                distance_task.setLoadListener(new CalculateDistanceTime.taskCompleteListener() {
                    @Override
                    public void taskCompleted(String[] time_distance) {
                        text1.setText(time_distance[0]); //Distance
                        text2.setText(time_distance[1]); //Time
                    }
                });

                String url = getDirectionsUrl(latLng1, markerOptions.getPosition());
                DownloadTask downloadTask = new DownloadTask();
                downloadTask.execute(url);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

CalculateDistanceTime.java(添加了新类)

class CalculateDistanceTime {     private taskCompleteListener
mTaskListener; private Context mContext;      
CalculateDistanceTime(Context context) {
mContext = context; }     void setLoadListener(taskCompleteListener taskListener) {
mTaskListener = taskListener; }        void getDirectionsUrl(LatLng origin, LatLng dest) {

// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;

// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;


// Sensor enabled
String sensor = "sensor=false";

// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;

// Output format
String output = "json";

// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;


DownloadTask downloadTask = new DownloadTask();

// Start downloading json data from Google Directions API

downloadTask.execute(url); }

private String downloadUrl(String strUrl) throws IOException {
String data = "";
HttpURLConnection urlConnection;
URL url = new URL(strUrl);

// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();

// Connecting to url
urlConnection.connect();

// Reading data from url
try (InputStream iStream = urlConnection.getInputStream()) {
    BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

    StringBuilder sb = new StringBuilder();

    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }

    data = sb.toString();

    br.close();

} catch (Exception e) {
    Log.d("Excp. while downloading", e.toString());
} finally {
    urlConnection.disconnect();
}
return data; }

interface taskCompleteListener {
void taskCompleted(String[] time_distance); }

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

// Downloading data in non-ui thread
@Override
protected String doInBackground(String... url) {

    // For storing data from web service
    String data = "";

    try {
        // Fetching the data from web service
        data = downloadUrl(url[0]);
    } catch (Exception e) {
        Log.d("Background Task", e.toString());
    }
    return data;
}

// Executes in UI thread, after the execution of
// doInBackground()
@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);

    ParserTask parserTask = new ParserTask();

    // Invokes the thread for parsing the JSON data
    parserTask.execute(result);

} }

private class ParserTask extends AsyncTask<String, Integer,
List<HashMap<String, String>>> {

// Parsing the data in non-ui thread
@Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {

    JSONObject jObject;
    List<HashMap<String, String>> routes = null;

    try {
        jObject = new JSONObject(jsonData[0]);
        DistanceTimeParser parser = new DistanceTimeParser();

        // Starts parsing data
        routes = parser.parse(jObject);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return routes;
}

// Executes in UI thread, after the parsing process
@Override
protected void onPostExecute(List<HashMap<String, String>> result) {

    String duration_distance = "";


    if (result.size() < 1) {
        Log.e("Error : ", "No Points found");
        return;
    }


    String[] date_dist = new String[2];

    // Traversing through all the routes
    for (int i = 0; i < result.size(); i++) {

        // Fetching i-th route
        HashMap<String, String> tmpData = result.get(i);
        Set<String> key = tmpData.keySet();
        Iterator it = key.iterator();
        while (it.hasNext()) {
            String hmKey = (String) it.next();
            duration_distance = tmpData.get(hmKey);

            System.out.println("Key: " + hmKey + " & Data: " + duration_distance);

            it.remove(); // avoids a ConcurrentModificationException
        }

        date_dist[i] = duration_distance;
    }

    mTaskListener.taskCompleted(date_dist);
}   } }

DistanceTimeParser.java(添加了新类)

public class DistanceTimeParser {
public List<HashMap<String, String>> parse(JSONObject jObject) {


    List<HashMap<String, String>> routes = new ArrayList<HashMap<String, String>>();
    JSONArray jRoutes = null;
    JSONArray jLegs = null;

    JSONObject jDistance = null;
    JSONObject jDuration = null;

    try {

        jRoutes = jObject.getJSONArray("routes");

        jLegs = ((JSONObject) jRoutes.get(0)).getJSONArray("legs");

        List<HashMap<String, String>> path = new ArrayList<HashMap<String, String>>();


        /** Getting distance from the json data */
        jDistance = ((JSONObject) jLegs.get(0)).getJSONObject("distance");
        HashMap<String, String> hmDistance = new HashMap<String, String>();
        hmDistance.put("distance", jDistance.getString("text"));

        /** Getting duration from the json data */
        jDuration = ((JSONObject) jLegs.get(0)).getJSONObject("duration");
        HashMap<String, String> hmDuration = new HashMap<String, String>();
        hmDuration.put("duration", jDuration.getString("text"));

        routes.add(hmDistance);

        routes.add(hmDuration);

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

    return routes;
} }

DirectionsJSONParser.java(添加了新类)

public class DirectionsJSONParser {

List<List<HashMap<String,String>>> parse(JSONObject jObject){

    List<List<HashMap<String, String>>> routes = new ArrayList<>() ;
    JSONArray jRoutes ;
    JSONArray jLegs ;
    JSONArray jSteps ;

    try {

        jRoutes = jObject.getJSONArray("routes");


        for(int i=0;i<jRoutes.length();i++){
            jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
            List path = new ArrayList<>();

            for(int j=0;j<jLegs.length();j++){
                jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");


                for(int k=0;k<jSteps.length();k++){
                    String polyline;
                    polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
                    List<LatLng> list = decodePoly(polyline);


                    for(int l=0;l<list.size();l++){
                        HashMap<String, String> hm = new HashMap<>();
                        hm.put("lat", Double.toString((list.get(l)).latitude) );
                        hm.put("lng", Double.toString((list.get(l)).longitude) );
                        path.add(hm);
                    }
                }
                routes.add(path);
            }
        }

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

    return routes;
}

private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng((((double) lat / 1E5)),
                (((double) lng / 1E5)));
        poly.add(p);
    }

    return poly;
} }

在mapsActivity.java中添加了这4个方法

  private String getDirectionsUrl(LatLng origin, LatLng dest) {

    String str_origin = "origin=" + origin.latitude + "," + origin.longitude;

    String str_dest = "destination=" + dest.latitude + "," + dest.longitude;

    String sensor = "sensor=false";

    String parameters = str_origin + "&" + str_dest + "&" + sensor;

    String output = "json";

    return "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
}

  @SuppressLint("NewApi")
  public static String downloadUrl(String strUrl) throws IOException {
    String data = "";
    HttpURLConnection urlConnection;
    URL url = new URL(strUrl);

    // Creating an http connection to communicate with url
    urlConnection = (HttpURLConnection) url.openConnection();

    // Connecting to url
    urlConnection.connect();

    // Reading data from url
    try (InputStream iStream = urlConnection.getInputStream()) {
        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

        StringBuilder sb = new StringBuilder();

        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        data = sb.toString();

        br.close();

    } catch (Exception e) {
        Log.d("Exception while down", e.toString());
    } finally {
        urlConnection.disconnect();
    }
    return data;
}

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

    // Downloading data in non-ui thread
    @Override
    protected String doInBackground(String... url) {

        // For storing data from web service
        String data = "";

        try {
            // Fetching the data from web service
            data = downloadUrl(url[0]);
        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        return data;
    }

    // Executes in UI thread, after the execution of
    // doInBackground()
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        ParserTask parserTask = new ParserTask();

        // Invokes the thread for parsing the JSON data
        parserTask.execute(result);
    }
}

private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {

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

        JSONObject jObject;
        List<List<HashMap<String, String>>> routes = null;

        try {
            jObject = new JSONObject(jsonData[0]);
            DirectionsJSONParser parser = new DirectionsJSONParser();

            // Starts parsing data
            routes = parser.parse(jObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return routes;
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        ArrayList<LatLng> points = new ArrayList<>();
        PolylineOptions lineOptions = new PolylineOptions();
        for (int i = 0; i < result.size(); i++) {
            List<HashMap<String, String>> path = result.get(i);
            for (int j = 0; j < path.size(); j++) {
                HashMap<String, String> point = path.get(j);
                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);
                points.add(position);
            }
            lineOptions.addAll(points);
            lineOptions.width(10);
            lineOptions.color(Color.WHITE);
            mMap.addPolyline(lineOptions);
        }
    }
}

mapsActivity.java(我在地图中的当前位置)

@Override
public void onLocationChanged(Location location) {
    Log.d("onLocationChanged", "entered");

    mLastLocation = location;

    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date date = new Date();
    mLastUpdateTime = ((dateFormat.format(date).toString()));

    saveToFirebase();

    if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
    }

    latitude = location.getLatitude();
    longitude = location.getLongitude();

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

    //move map camera
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(11));

    Toast.makeText(MapsActivity.this, "Your Current Location", Toast.LENGTH_LONG).show();

    //stop location updates
    if (mGoogleApiClient != null) {
     LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
   this);
        Log.d("onLocationChanged", "Removing Location Updates");
    }
}

Fire Base 方法中保存的数据

public void saveToFirebase() {

    DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Email").push();
    String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
    UserInformation userInformation = new UserInformation(email, mLastLocation.getLatitude(), mLastLocation.getLongitude());
    ref.setValue(userInformation);
}

我假设您需要路线、距离和时间。 首先创建这3个类。

  1. 计算距离时间.java

    import android.content.Context;
    import android.os.AsyncTask;
    import android.util.Log;    
    import com.google.android.gms.maps.model.LatLng;    
    import org.json.JSONObject;    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Set;    
    class CalculateDistanceTime {    
    private taskCompleteListener mTaskListener;
    private Context mContext;      
    CalculateDistanceTime(Context context) {
        mContext = context;
    }    
    void setLoadListener(taskCompleteListener taskListener) {
        mTaskListener = taskListener;
    }       
    void getDirectionsUrl(LatLng origin, LatLng dest) {
    
        // Origin of route
        String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
    
        // Destination of route
        String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
    
    
        // Sensor enabled
        String sensor = "sensor=false";
    
        // Building the parameters to the web service
        String parameters = str_origin + "&" + str_dest + "&" + sensor;
    
        // Output format
        String output = "json";
    
        // Building the url to the web service
        String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
    
    
        DownloadTask downloadTask = new DownloadTask();
    
        // Start downloading json data from Google Directions API
    
        downloadTask.execute(url);
    }
    
    private String downloadUrl(String strUrl) throws IOException {
        String data = "";
        HttpURLConnection urlConnection;
        URL url = new URL(strUrl);
    
        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();
    
        // Connecting to url
        urlConnection.connect();
    
        // Reading data from url
        try (InputStream iStream = urlConnection.getInputStream()) {
            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
    
            StringBuilder sb = new StringBuilder();
    
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
    
            data = sb.toString();
    
            br.close();
    
        } catch (Exception e) {
            Log.d("Excp. while downloading", e.toString());
        } finally {
            urlConnection.disconnect();
        }
        return data;
    }
    
    
    interface taskCompleteListener {
        void taskCompleted(String[] time_distance);
    }
    
    private class DownloadTask extends AsyncTask<String, Void, String> {
    
        // Downloading data in non-ui thread
        @Override
        protected String doInBackground(String... url) {
    
            // For storing data from web service
            String data = "";
    
            try {
                // Fetching the data from web service
                data = downloadUrl(url[0]);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }
    
        // Executes in UI thread, after the execution of
        // doInBackground()
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
    
            ParserTask parserTask = new ParserTask();
    
            // Invokes the thread for parsing the JSON data
            parserTask.execute(result);
    
        }
    }
    
    private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
    
        // Parsing the data in non-ui thread
        @Override
        protected List<HashMap<String, String>> doInBackground(String... jsonData) {
    
            JSONObject jObject;
            List<HashMap<String, String>> routes = null;
    
            try {
                jObject = new JSONObject(jsonData[0]);
                DistanceTimeParser parser = new DistanceTimeParser();
    
                // Starts parsing data
                routes = parser.parse(jObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return routes;
        }
    
        // Executes in UI thread, after the parsing process
        @Override
        protected void onPostExecute(List<HashMap<String, String>> result) {
    
            String duration_distance = "";
    
    
            if (result.size() < 1) {
                Log.e("Error : ", "No Points found");
                return;
            }
    
    
            String[] date_dist = new String[2];
    
            // Traversing through all the routes
            for (int i = 0; i < result.size(); i++) {
    
                // Fetching i-th route
                HashMap<String, String> tmpData = result.get(i);
                Set<String> key = tmpData.keySet();
                Iterator it = key.iterator();
                while (it.hasNext()) {
                    String hmKey = (String) it.next();
                    duration_distance = tmpData.get(hmKey);
    
                    System.out.println("Key: " + hmKey + " & Data: " + duration_distance);
    
                    it.remove(); // avoids a ConcurrentModificationException
                }
    
                date_dist[i] = duration_distance;
            }
    
            mTaskListener.taskCompleted(date_dist);
        }
      }
    }
    
  2. 距离时间解析器.java

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    
    public class DistanceTimeParser {
        public List<HashMap<String, String>> parse(JSONObject jObject) {
    
    
        List<HashMap<String, String>> routes = new ArrayList<HashMap<String, String>>();
        JSONArray jRoutes = null;
        JSONArray jLegs = null;
    
        JSONObject jDistance = null;
        JSONObject jDuration = null;
    
        try {
    
            jRoutes = jObject.getJSONArray("routes");
    
            jLegs = ((JSONObject) jRoutes.get(0)).getJSONArray("legs");
    
            List<HashMap<String, String>> path = new ArrayList<HashMap<String, String>>();
    
    
            /** Getting distance from the json data */
            jDistance = ((JSONObject) jLegs.get(0)).getJSONObject("distance");
            HashMap<String, String> hmDistance = new HashMap<String, String>();
            hmDistance.put("distance", jDistance.getString("text"));
    
            /** Getting duration from the json data */
            jDuration = ((JSONObject) jLegs.get(0)).getJSONObject("duration");
            HashMap<String, String> hmDuration = new HashMap<String, String>();
            hmDuration.put("duration", jDuration.getString("text"));
    
            routes.add(hmDistance);
    
            routes.add(hmDuration);
    
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
        }
    
        return routes;
    }
    }
    
  3. DirectionsJSONParser.java

    import com.google.android.gms.maps.model.LatLng;    
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    class DirectionsJSONParser {
    
    
    List<List<HashMap<String,String>>> parse(JSONObject jObject){
    
        List<List<HashMap<String, String>>> routes = new ArrayList<>() ;
        JSONArray jRoutes ;
        JSONArray jLegs ;
        JSONArray jSteps ;
    
        try {
    
            jRoutes = jObject.getJSONArray("routes");
    
    
            for(int i=0;i<jRoutes.length();i++){
                jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList<>();
    
                for(int j=0;j<jLegs.length();j++){
                    jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
    
    
                    for(int k=0;k<jSteps.length();k++){
                        String polyline;
                        polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);
    
    
                        for(int l=0;l<list.size();l++){
                            HashMap<String, String> hm = new HashMap<>();
                            hm.put("lat", Double.toString((list.get(l)).latitude) );
                            hm.put("lng", Double.toString((list.get(l)).longitude) );
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }
    
        } catch (JSONException e) {
            e.printStackTrace();
        }catch (Exception ignored){
        }
    
        return routes;
    }
    
    private List<LatLng> decodePoly(String encoded) {
    
        List<LatLng> poly = new ArrayList<>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;
    
        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;
    
            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;
    
            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }
    
        return poly;
    }
    }
    

简单复制这三个文件后。 您可以对任何 MapsActivity 执行以下操作。
您可以在任何活动中使用下面的代码,并且上面的代码对于每个活动(方向地图)都保持相同。

创建全局变量CalculateDistanceTime distance_task;.
将其初始化在onCreate as distance_task = new CalculateDistanceTime(this);

将这 4 个方法发布到您的 MapsActivity.java 中。

private String getDirectionsUrl(LatLng origin, LatLng dest) {

        String str_origin = "origin=" + origin.latitude + "," + origin.longitude;


        String str_dest = "destination=" + dest.latitude + "," + dest.longitude;


        String sensor = "sensor=false";


        String parameters = str_origin + "&" + str_dest + "&" + sensor;

        String output = "json";


        return "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
    }

    public static String downloadUrl(String strUrl) throws IOException {
        String data = "";
        HttpURLConnection urlConnection;
        URL url = new URL(strUrl);

        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        try (InputStream iStream = urlConnection.getInputStream()) {
            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuilder sb = new StringBuilder();

            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            data = sb.toString();

            br.close();

        } catch (Exception e) {
            Log.d("Exception while down", e.toString());
        } finally {
            urlConnection.disconnect();
        }
        return data;
    }

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

        // Downloading data in non-ui thread
        @Override
        protected String doInBackground(String... url) {

            // For storing data from web service
            String data = "";

            try {
                // Fetching the data from web service
                data = downloadUrl(url[0]);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }

        // Executes in UI thread, after the execution of
        // doInBackground()
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            ParserTask parserTask = new ParserTask();

            // Invokes the thread for parsing the JSON data
            parserTask.execute(result);
        }
    }

private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {

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

            JSONObject jObject;
            List<List<HashMap<String, String>>> routes = null;

            try {
                jObject = new JSONObject(jsonData[0]);
                DirectionsJSONParser parser = new DirectionsJSONParser();

                // Starts parsing data
                routes = parser.parse(jObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return routes;
        }

        @Override
        protected void onPostExecute(List<List<HashMap<String, String>>> result) {
            ArrayList<LatLng> points = new ArrayList<>();
            lineOptions = new PolylineOptions();
            for (int i = 0; i < result.size(); i++) {
                List<HashMap<String, String>> path = result.get(i);
                for (int j = 0; j < path.size(); j++) {
                    HashMap<String, String> point = path.get(j);
                    double lat = Double.parseDouble(point.get("lat"));
                    double lng = Double.parseDouble(point.get("lng"));
                    LatLng position = new LatLng(lat, lng);
                    points.add(position);
                }
                lineOptions.addAll(points);
                lineOptions.width(10);                   
                lineOptions.color(Color.WHITE);
                googleMap.addPolyline(lineOptions);                
        }
    }

此时您已拥有所需的所有代码。
现在使用以下代码传递您的位置和朋友的位置的纬度,您将获得时间距离和路线:

               distance_task.getDirectionsUrl(latLng1, latLng2);
               distance_task.setLoadListener(new CalculateDistanceTime.taskCompleteListener() {
                        @Override
                        public void taskCompleted(String[] time_distance) {
                            text1.setText(time_distance[0]); //Distance
                            text2.setText(time_distance[1]); //Time
                        }
                    });
               String url = getDirectionsUrl(latLng1, latLng2);
               DownloadTask downloadTask = new DownloadTask();
               downloadTask.execute(url);

为了显示距离和时间,您必须创建两个TextView(参见上面的文本 1 和文本 2)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

两个位置之间不显示折线,但显示时间和距离 的相关文章

  • Flutter 深度链接

    据Flutter官方介绍深层链接页面 https flutter dev docs development ui navigation deep linking 我们不需要任何插件或本机 Android iOS 代码来处理深层链接 但它并没
  • 检查 Android 手机上的方向

    如何查看Android手机是横屏还是竖屏 当前配置用于确定要检索的资源 可从资源中获取Configuration object getResources getConfiguration orientation 您可以通过查看其值来检查方向
  • 反思 Groovy 脚本中声明的函数

    有没有一种方法可以获取 Groovy 脚本中声明的函数的反射数据 该脚本已通过GroovyShell目的 具体来说 我想枚举脚本中的函数并访问附加到它们的注释 Put this到 Groovy 脚本的最后一行 它将作为脚本的返回值 a la
  • 如何在 JFreeChart TimeSeries 图表上显示降雨指数和温度?

    目前 我的 TimeSeries 图表每 2 秒显示一个位置的温度 现在 如果我想每2秒显示一次降雨指数和温度 我该如何实现呢 这是我的代码 import testWeatherService TestWeatherTimeLapseSer
  • 材质设计图标颜色

    应该是哪种颜色 暗 材质图标 在官方文档上 https www google com design spec style icons html icons system icons https www google com design s
  • 调节麦克风录音音量

    我们正在尝试调整录音时的音量级别 麦克风似乎非常敏感 会接收到很多静电 我们查看了 setVolumeControlStream 但找不到传入其中来控制麦克风的流 将您的音频源设置为 MIC using MediaRecorder Audi
  • Java直接内存:在自定义类中使用sun.misc.Cleaner

    在 Java 中 NIO 直接缓冲区分配的内存通过以下方式释放 sun misc Cleaner实例 一些比对象终结更有效的特殊幻像引用 这种清洁器机制是否仅针对直接缓冲区子类硬编码在 JVM 中 或者是否也可以在自定义组件中使用清洁器 例
  • Android 设备上的静默安装

    我已经接受了一段时间了 在 Android 上静默安装应用程序是不可能的 也就是说 让程序安装捆绑为 APK 的应用程序 而不提供标准操作系统安装提示并完成应用程序安装程序活动 但现在我已经拿到了 Appbrain 快速网络安装程序的副本
  • 通过 ADB 拔出设备:“找不到服务”

    我必须测试我的应用程序在打瞌睡模式下的行为 根据文档 https developer android com training monitoring device state doze standby html testing doze 我
  • 应用程序关闭时的倒计时问题

    我制作了一个 CountDownTimer 代码 我希望 CountDownTimer 在完成时重新启动 即使应用程序已关闭 但它仅在应用程序正在运行或重新启动应用程序时重新启动 因此 如果我在倒计时为 00 10 分钟 秒 时关闭应用程序
  • 使用 SAX 进行 XML 解析 |如何处理特殊字符?

    我们有一个 JAVA 应用程序 可以从 SAP 系统中提取数据 解析数据并呈现给用户 使用 SAP JCo 连接器提取数据 最近我们抛出了一个异常 org xml sax SAXParseException 字符引用 是无效的 XML 字符
  • Windows 上的 Nifi 命令

    在我当前的项目中 我一直在Windows操作系统上使用apache nifi 我已经提取了nifi 0 7 0 bin zip文件输入C 现在 当我跑步时 bin run nifi bat as 管理员我在命令行上看到以下消息 但无法运行
  • 运行 Jar 文件时出现问题

    我已将 java 项目编译成 Jar 文件 但运行它时遇到问题 当我跑步时 java jar myJar jar 我收到以下错误 Could not find the main class myClass 类文件不在 jar 的根目录中 因
  • Springs 元素“beans”不能具有字符 [children],因为该类型的内容类型是仅元素

    我在 stackoverflow 中搜索了一些页面来解决这个问题 确实遵循了一些正确的答案 但不起作用 我是春天的新人 对不起 这是我的调度程序 servlet
  • 休眠以持久保存日期

    有没有办法告诉 Hibernate java util Date 应该持久保存 我需要这个来解决 MySQL 中缺少的毫秒分辨率问题 您能想到这种方法有什么缺点吗 您可以自己创建字段long 或者使用自定义的UserType 实施后User
  • com.jcraft.jsch.JSchException:身份验证失败

    当我从本地磁盘上传文件到远程服务器时 出现这样的异常 com jcraft jsch JSchException Auth fail at org apache tools ant taskdefs optional ssh Scp exe
  • 为什么Android的ImageReader类这么慢?

    我尝试了适用于 Android 3 4 1 的全新 OpenCVJavaCamera2View但它太慢了 仅显示相机视图约 15 fps 当我尝试较旧的JavaCameraView相反 它给了我很好的结果 30fps 这是我相机的极限 我想
  • 无法将 admob 与 firebase iOS/Android 项目链接

    我有两个帐户 A 和 B A 是在 Firebase 上托管 iOS Android unity 手机游戏的主帐户 B 用于将 admob 集成到 iOS Android 手机游戏中 我在尝试将 admob 分析链接到 Firebase 项
  • JAVA - 如何从扫描仪读取文件中检测到“\n”字符

    第一次海报 我在读取文本文件的扫描仪中读取返回字符时遇到问题 正在读取的文本文件如下所示 test txt start 2 0 30 30 1 1 90 30 0 test txt end 第一行 2 表示两个点 第二行 位置索引 0 xp
  • Swagger/Openapi-Annotations:如何使用 $ref 生成 allOf?

    我正在生成 Rest 端点 包括添加OpenAPI Swagger对生成的代码进行注释 虽然它对于基本类型运行得很好 但我在自定义类方面遇到了一些问题 现在我有很多自定义类的重复架构条目 使用 Schema 实现 MyClass class

随机推荐

  • array_agg() 的替代品?

    有没有 PostgreSQL 的替代品array agg 函数 以便它不会返回以下格式的值 x y z 我可以让它返回吗 x y z In PostgreSQL 9 0或稍后使用string agg val https www postgr
  • wglShareLists 失败并出现错误 6:ERROR_INVALID_HANDLE 句柄无效

    我尝试在两个类之间共享 HPBUFFERARB TGLForm 和 TGLForm2 我尝试过 FBO 但有一个旧的 Borland Builder 6 版本 我无法使用 FBO 进行管理 我的目标是在两个 openGL 窗口中显示相同的缓
  • CSS 浮动页脚

    我想制作一个保留在可视窗口底部的页脚 除非当您调整窗口大小时它会与内容相抵触 我试过 底部 0 位置 绝对 但是当窗口较小时 页脚会妨碍 我相信这会做你想要的 CSS 布局 100 高度 包含页眉和页脚 http www xs4all nl
  • 按组顺序填充 NA 值

    我正在尝试填充数据集中的一些值 我的数据的简化版本如下 gt example df Date GROUP value 157 2018 01 31 10180 3 464 158 2018 02 28 10180 3 413 159 201
  • 将 Javascript 应用程序转换为 Windows 应用程序

    除了Adobe Air还有其他解决方案吗 我听说 V8 有点东西 只是现在没有时间 用另一种语言编写整个应用程序 然后编写 2 倍以上的代码 也许你可以使用jsc 从命令行编译 JScript 代码 http msdn microsoft
  • 如何在 Azure 中允许 URL 编码路径段

    我有一个在 Azure 中运行的 ASP NET 6 MVC 应用程序 我有一个控制器 其动作如下 HttpDelete Route image url public async Task
  • 使用柏林噪声来创造闪电?

    实际上 我有几个与主题标题中给出的主题相关的问题 我已经在我的应用程序中使用 Perlin 函数创建闪电 但我对我的实现并不完全满意 以下问题基于初始和改进的 Perlin 噪声实现 为了简化问题 我们假设我通过使用 1D Perlin 函
  • 我可以有两个 Fancybox 2.0 实例吗?

    我在我的网站上安装了 Fancybox 2 0 稍加修改使其看起来像 Facebook 图像预览框 我想要有 Fancybox 的第二个 实例 但它的定位不同 我的图像预览 Fancybox 当前实例 应距顶部 20 像素 目前 但我的共享
  • 使用 jquery 根据 4 个输入的总和设置数字输入最大值

    我有 4 个输入字段 我需要所有字段的总数不超过 100 我想设置要更改的字段的最大值 我一直在尝试调整 keyup 上的值 然后将其他字段的总和与当前字段的总和相区别并设置最大值 似乎工作了一段时间然后就停止了 JSfiddle 示例 h
  • Docker 添加当前目录中的每个文件

    我有一个简单的 Web 应用程序 我想将其放置在 docker 容器中 角度应用程序存在于frontend 文件夹 该文件夹位于application folder 当 Dockerfile 位于application 文件夹 内容如下 F
  • 有没有一种简单的方法可以从 python 中的无空格句子生成可能的单词列表?

    我有一些文字 s Imageclassificationmethodscan beroughlydividedinto two broad families of approaches 我想将其解析为单独的单词 我很快地研究了附魔和nltk
  • Pytorch 0.4.0:可以通过三种方式在 CUDA 设备上创建张量。他们之间有什么区别吗?

    我第三条路失败了 t3仍在CPU上 不知道为什么 a np random randn 1 1 2 3 t1 torch tensor a t1 t3 to torch device cuda t2 torch tensor a t2 t2
  • 在 php 中为多个图像上传创建缩略图时出错

    我使用以下代码上传 重命名 压缩 创建缩略图一切正常 最近我注意到在创建缩略图时 它还会为以前上传的图像创建缩略图图像的新副本 也为上传的图像创建缩略图 Problem 提交表单后 它会生成用于上传图像和已上传图像 较旧版本中存在的图像文件
  • 无法加载文件或程序集“Oracle.DataAccess”64 位 ODP.NET

    我在用ODP NET在我的 asp net 项目中 以便应用程序能够与 Windows 2008 服务器 32 位 上的 Oracle 11 g Express 进行通信 在开发机器上 我使用的是 Windows 7 32 位 我在开发计算
  • 未找到特征“Spatie\MediaLibrary\HasMedia\HasMediaTrait”

    它显示错误 无法获取 HasMedia 红色字体 的命名空间和 HasMediaTrait 的未定义类 第 16 行 有什么想法吗 None
  • 查找元素彼此相距最远的子集

    我有一个面试问题 我似乎无法弄清楚 给定一个大小为 N 的数组 找到大小为 k 的子集 使得子集中的元素彼此相距最远 换句话说 最大化元素之间的最小成对距离 Example Array 1 2 6 10 k 3 answer 1 6 10
  • 将 HTML 表解析为 CSV 的最佳方法

    我必须从现有网站上获取一些产品数据并将其放入数据库中 数据全部采用 HTML 表格格式 型号是唯一的 但每个产品可以有任意数量的不同属性 因此我需要解析的表格都有不同的列和标题 table tr td Model No td td Weig
  • 在 html 页面上显示命令行输出

    我正在构建一个网络应用程序 它在终端上运行某些命令并将结果显示回网络应用程序上 我能够使用 child process exec 运行命令并获取我面临的问题的结果 同时将其显示在 html 页面上 I want something like
  • ExtJs 4 组合框缺少配置选项hiddenName

    我正在尝试创建一个 ExtJs 版本 4 ComboBox 它将发布 valueField 而不是 displayValue 之前的版本是在 ComboBox 的配置中设置 hiddenName 选项 但我似乎无法在 v 4 或等效版本中找
  • 两个位置之间不显示折线,但显示时间和距离

    注意 抱歉我的英语不好 因为英语不是我的母语 我为此使用了谷歌翻译 我正在开发一个 Android 地图应用程序 用户可以在其中找到朋友的当前位置 为了存储当前位置 我使用 Firebase 实时数据库 在 Lalit Singh 之前的帮