Is there a way to show road directions in Google Map API v2? [duplicate]

半世苍凉 提交于 2019-12-17 16:33:14

问题


I was looking for an answer using Google and here, and the only relevant posts I have found are:

Google Maps Android V2 and Direction API

Get driving directions using Google Maps API v2

but there is no answer there. So I have already mentioned it but I will say that again. I am looking for a solution for the Google Map API v2 using FragmentActivity and a SupportMagFragment and LatLng objects and not using MapView ,MapActivity and GeoPoint.

In addition I don't have the Overlay object to use so I can't paint the direction on the map, is there an alternative for that?

So is there a way to do that?


回答1:


Try this solution here. You can get driving or walking direction on V2.




回答2:


The Overlay is indeed something to forget.

Polylines can easily be drawn

https://developers.google.com/maps/documentation/android/lines#add_a_polyline

Just loop through yourr points after you parsed tjhe JSON response:

PolylineOptions rectOptions = new PolylineOptions()
        .add(new LatLng(37.35, -122.0))
        .add(new LatLng(37.45, -122.0))  // North of the previous point, but at the same longitude
        .add(new LatLng(37.45, -122.2))  // Same latitude, and 30km to the west
        .add(new LatLng(37.35, -122.2))  // Same longitude, and 16km to the south
        .add(new LatLng(37.35, -122.0)); // Closes the polyline.

// Set the rectangle's color to red
rectOptions.color(Color.RED);

// Get back the mutable Polyline
Polyline polyline = myMap.addPolyline(rectOptions);



回答3:


Your question title is much more general than your requirements, so I will answer this in a way that I think will benefit those viewing this question and hopefully meet your requirements in perhaps a different way.

If you are not showing directions in the context of a map already being a loaded fragment and something having been done to show directions over the map (which is probably similar to what the OP is doing), it's easier and I believe standard to do this with an Intent.

This launches a map pathing activity (through a separate application - where the app launched depends on the user's compatible apps, which by default is Google Maps) that plots directions from the origin address (String originAddress) to the destination address (String destinationAddress) via roadways:

// Build the URI query string.
String uriPath = "https://www.google.com/maps/dir/";
// Format parameters according to documentation at:
// https://developers.google.com/maps/documentation/directions/intro
String uriParams = 
    "?api=1" +
    "&origin=" + originAddress.replace(" ", "+")
        .replace(",", "") +
    "&destination=" + destinationAddress.replace(" ", "+")
        .replace(",", "") +
    "&travelmode=driving";
Uri queryURI = Uri.parse(uriPath + uriParams);
// Open the map.
Intent intent = new Intent(Intent.ACTION_VIEW, queryURI);
startActivity(activity, intent, null);

(Where activity is simply the currently active Activity - obtained through whatever means are appropriate in the current programming context).

The following code gets an address String from a LatLng object (which must then be processed for the URI query String as above):

/**
* Retrieves an address `String` from a `LatLng` object.
*/
private void getAddressFromLocation(
    final StringBuilder address, final LatLng latlng) {
    // Create the URI query String.
    String uriPath = 
        "https://maps.googleapis.com/maps/api/geocode/json";
    String uriParams = 
        "?latlng=" + String.format("%f,%f",
            latlng.latitude, latlng.longitude) +
        "&key=" + GOOGLE_MAPS_WEB_API_KEY;
    String uriString = uriPath + uriParams;
    // Issue the query using the Volley library for networking.
    RequestFuture<JSONObject> future = RequestFuture.newFuture();
    JSONObject response = null;
    // Required for JsonObjectRequest, but not important here.
    Map<String, String> jsonParams = new HashMap<String, String>();
    JsonObjectRequest request = 
        new JsonObjectRequest(Request.Method.POST, 
            uriString,
            new JSONObject(jsonParams),
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        if (response != null) {
                            String resultString =
                                response.getJSONArray("results")
                                        .getJSONObject(0)
                                        .getString("formatted_address");
                            // Assumes `address` was empty.
                            address.append(resultString);
                        } // end of if
                        // No response was received.
                    } catch (JSONException e) {
                        // Most likely, an assumption about the JSON 
                        // structure was invalid.
                        e.printStackTrace();
                    }
                } // end of `onResponse()`
            }, // end of `new Response.Listener<JSONObject>()`
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(LOG_TAG, "Error occurred ", error);
                }
            });
    // Add the request to the request queue.
    // `VolleyRequestQueue` is a singleton containing
    // an instance of a Volley `RequestQueue`.
    VolleyRequestQueue.getInstance(activity)
        .addToRequestQueue(request);
}

This request is asynchronous, but it can be made synchronous. You will need to call toString() on the actual parameter passed to address to obtain originAddress.




回答4:


Q:I was looking for an answer using Google and here, and the only relevant posts i have found are: Google Maps Android V2 and Direction API Google map API v2 - get driving directions

Answer: Your saying, "but there is no answer there." is not absolutely right. In this site, you can find just only a few clues about that. I think you will not get the perfect code and concrete implement KNOW-HOWs here. In fact, many developers want to make the app to display the routing or directions on Google Maps. But I think there is no solution to get directions just only with the pure Google Maps API v2.

Q: So I have already mentioned it but I will say that again. I am looking for a solution for the Google Map API v2 using FragmentActivity and a SupportMagFragment and LatLng objects and not using MapView ,MapActivtiy and GeoPoint.

Answer: Here are a few good sample tutorials (click here). You can find what you want.

Q: In addition i don't have the Overlay object to use so i can't paint the direction on the map, is there an alternative for that? So is there a way to do that?

Answer: In the Google Maps API v2, the annoying Overlay and so on are not any more required. For this, you can find the answer in my linked site above.



来源:https://stackoverflow.com/questions/14554078/is-there-a-way-to-show-road-directions-in-google-map-api-v2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!