您的问题标题比您的要求更笼统,因此我将以一种我认为对查看此问题的人有益的方式回答这个问题,并希望以不同的方式满足您的要求。
如果您没有在已经加载的片段的地图上下文中显示方向,并且已经做了一些事情来显示地图上的方向(这可能类似于 OP 正在做的事情),那么它会更容易并且我相信这样做是标准的带有Intent
.
这将启动一个地图路径活动(通过一个单独的应用程序 - 启动的应用程序取决于用户的兼容应用程序,默认情况下是谷歌地图),该活动绘制从起始地址 ( String originAddress
) 到目的地地址 ( String destinationAddress
) 通过道路的方向:
// 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);
(在哪里activity
只是当前活动的Activity
- 通过当前编程上下文中适当的任何方式获得)。
下面的代码String
从一个LatLng
对象中获取一个地址(然后必须String
为上面的 URI 查询进行处理):
/**
* 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);
}
此请求是异步的,但可以设为同步。您将需要调用toString()
传递给的实际参数address
来获取originAddress
.