当前位置: 首页 > 面试题库 >

Google路线从当前位置到已知位置的路线

郭远
2023-03-14
问题内容

MapsActivity在这个项目中使用该类。在我的地图上,您可以看到许多标记。我有许多已知的位置,但是在我的代码中,例如,我仅显示两个位置。

我不明白如何使用方向API和JSON。如何显示从当前位置(更改)到已知位置(恒定)的路线,距离和行进时间?

public class MapsActivity extends FragmentActivity {

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.
    private Map<Marker, Class<?>> allMarkersMap = new HashMap<Marker, Class<?>>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        setUpMapIfNeeded();
    }

    private void setUpMap() {
        Marker marker1 = mMap.addMarker(new MarkerOptions()
                .position(new LatLng(14.608177, 120.967422))
                .title("Sample2")
                .snippet("zzzzzzz"));
        allMarkersMap.put(marker1, MainActivity.class);

        Marker marker2 = mMap.addMarker(new MarkerOptions()
                .position(new LatLng(14.611335, 120.962160))
                .title("Sample1")
                .snippet("sssssss"));
        allMarkersMap.put(marker2, MainActivity2Activity.class);
        mMap.setMyLocationEnabled(true);

        mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {
                Class<?> cls = allMarkersMap.get(marker);
                        Intent intent = new Intent(MapsActivity.this, cls);
                startActivity(intent);
            }
        });
    }

问题答案:

看一下本教程:

使用Google Map Android API V2中的Google
Directions在两个位置之间绘制行车路线

它显示了如何在两点之间绘制路线图,计算距离和旅行时间。

如果您在遵循本教程时遇到问题,请从下面的链接下载Android Studio示例项目:

MapDemo.zip

public class DirectionsJSONParser {

    /** Receives a JSONObject and returns a list of lists containing latitude and longitude */
    public List<List<HashMap<String,String>>> parse(JSONObject jObject){

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

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for(int i=0;i<jRoutes.length();i++){
                jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList<HashMap<String, String>>();

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

                    /** Traversing all 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);

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

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

    return routes;
    }
    /**
    * Method to decode polyline points
    * Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
    * */
    private List<LatLng> decodePoly(String encoded) {

        List<LatLng> poly = new ArrayList<LatLng>();
        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;
    }
}
MainActivity.Java

public class MainActivity extends FragmentActivity {

GoogleMap map;
ArrayList<LatLng> markerPoints;
TextView tvDistanceDuration;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tvDistanceDuration = (TextView) findViewById(R.id.tv_distance_time);

    // Initializing
    markerPoints = new ArrayList<LatLng>();

    // Getting reference to SupportMapFragment of the activity_main
    SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

    // Getting Map for the SupportMapFragment
    map = fm.getMap();

    // Enable MyLocation Button in the Map
    map.setMyLocationEnabled(true);

    // Setting onclick event listener for the map
    map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

        @Override
        public void onMapClick(LatLng point) {

            // Already two locations
            if (markerPoints.size() > 1) {
                markerPoints.clear();
                map.clear();
            }

            // Adding new item to the ArrayList
            markerPoints.add(point);

            // Creating MarkerOptions
            MarkerOptions options = new MarkerOptions();

            // Setting the position of the marker
            options.position(point);

            /**
             * For the start location, the color of marker is GREEN and
             * for the end location, the color of marker is RED.
             */
            if (markerPoints.size() == 1) {
                options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
            } else if (markerPoints.size() == 2) {
                options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
            }

            // Add new marker to the Google Map Android API V2
            map.addMarker(options);

            // Checks, whether start and end locations are captured
            if (markerPoints.size() >= 2) {
                LatLng origin = markerPoints.get(0);
                LatLng dest = markerPoints.get(1);

                // Getting URL to the Google Directions API
                String url = getDirectionsUrl(origin, dest);

                DownloadTask downloadTask = new DownloadTask();

                // Start downloading json data from Google Directions API
                downloadTask.execute(url);
            }
        }
    });
}

private String 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;

    return url;
}

/**
 * A method to download json data from url
 */
private String downloadUrl(String strUrl) throws IOException {
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try {
        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
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

        StringBuffer sb = new StringBuffer();

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

        data = sb.toString();

        br.close();

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

// Fetches data from url passed
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);
    }
}

/**
 * A class to parse the Google Places in JSON format
 */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {

    // Parsing the data in non-ui thread
    @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;
    }

    // Executes in UI thread, after the parsing process
    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        ArrayList<LatLng> points = null;
        PolylineOptions lineOptions = null;
        MarkerOptions markerOptions = new MarkerOptions();
        String distance = "";
        String duration = "";

        if (result.size() < 1) {
            Toast.makeText(getBaseContext(), "No Points", Toast.LENGTH_SHORT).show();
            return;
        }

        // Traversing through all the routes
        for (int i = 0; i < result.size(); i++) {
            points = new ArrayList<LatLng>();
            lineOptions = new PolylineOptions();

            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // Fetching all the points in i-th route
            for (int j = 0; j < path.size(); j++) {
                HashMap<String, String> point = path.get(j);

                if (j == 0) {    // Get distance from the list
                    distance = (String) point.get("distance");
                    continue;
                } else if (j == 1) { // Get duration from the list
                    duration = (String) point.get("duration");
                    continue;
                }

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(2);
            lineOptions.color(Color.RED);
        }

        tvDistanceDuration.setText("Distance:" + distance + ", Duration:" + duration);

        // Drawing polyline in the Google Map for the i-th route
        map.addPolyline(lineOptions);
    }
}


 类似资料:
  • 我意识到这个问题以前被问过很多次,但我现在问这个问题是因为答案很旧(与新的API相比)。 我以前使用过Location Manager,但我发现它非常不可靠。例如,在我的应用程序中,使用getLastKnownLocation和/或current location,它会立即将相机加载到用户的当前位置。但是,如果我在启动应用程序之前打开设备上的位置,它就不会把摄像头放在用户的当前位置,而是放在Nig

  • 问题内容: 好的,所以我对Mapbox还是很陌生,在此之前我曾经使用过GMaps,但是我发现Mapbox能够满足我的需要,问题是我碰壁了。 我使用了他们网站上可用示例的组合 https://www.mapbox.com/android- sdk/examples/geocoding 和 https://www.mapbox.com/android- sdk/examples/directions

  • 我正在创建一个带有谷歌地图视图的应用程序,我想让这个应用程序检测用户的当前位置,并在地图上显示带有标记的lat和long,但我现在所能做的只是显示谷歌地图和检测当前位置,而不显示任何标记,也不显示任何文本来显示lat和long 直到现在我才添加一个标记,因为我不知道该把它放在代码中的什么位置,以及这样做的最佳实践是什么 有人能帮我吗???这是的代码:

  • 我正在尝试使用Maps API V2来更加熟悉它,并且我正在尝试以用户当前位置为中心启动地图。使用语句,我可以在地图上显示我的当前位置。这也将按钮添加到UI中,使地图以我当前的位置为中心。 我想在我的代码中模拟按钮按下。我熟悉和类,并且认识到使用这些类是一种可行的替代方法,但是将用户位置居中和放大的功能似乎已经通过按钮内置了。

  • 问题内容: 我正在尝试使用新的Google Maps Android API V2,并且正在 为Android 2.3.3或更高版本开发应用程序。这是一个非常简单的应用程序:它将用户的当前 位置(使用gps或网络信号)从数据库中获取 ,并使用方向api 获得POI ,它将用户带到POI。 我的问题是获取用户当前位置。感谢这篇文章如何在Google Maps Android API v2中获取当前位