Google Map Directions Api v2 无法执行路线/路径请求
Posted
技术标签:
【中文标题】Google Map Directions Api v2 无法执行路线/路径请求【英文标题】:Google Map Directions Api v2 can't perform route/path request 【发布时间】:2020-07-01 13:19:14 【问题描述】:我正在尝试在我的应用中实现一项功能,该功能使用 Google Maps API Directions 在地图中绘制路径(从 A 到 B)。由于某种原因,应用程序似乎甚至无法发出请求。总是取result.size()<1
的情况
protected void onPostExecute(List<List<HashMap<String, String>>> result)
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
String distance = "";
String duration = "";
dialogz.dismiss();
if(result.size()<1)
Toast.makeText(getBaseContext(), "Road name cannot be identified, Please choose a nearest location", Toast.LENGTH_SHORT).show();
return;
for(int i=0;i<result.size();i++)
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
List<HashMap<String, String>> path = result.get(i);
for(int j=0;j<path.size();j++)
HashMap<String,String> point = path.get(j);
if(j==0)
distance = (String)point.get("distance");
continue;
else if(j==1)
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(18);
lineOptions.color(Color.parseColor("#2E2E2E"));
---and this is the code of getDirectionUrl----
private void getDirectionsUrl(LatLng picklatlng,LatLng droplatlng)
if(picklatlng!=null && droplatlng!=null)
String str_origin = "origin=" + picklatlng.latitude + "," + picklatlng.longitude;
String str_dest = "destination=" + droplatlng.latitude + "," + droplatlng.longitude;
String sensor = "sensor=false";
String parameters = str_origin + "&" + str_dest + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
【问题讨论】:
【参考方案1】:您的代码看起来不错,但我没有看到您正在向 Directions API 请求添加API key。
确保您添加了一个(不受限制的)一个,它不能与您用于加载 Google 地图的那个相同(假设 API 密钥是 android 限制的 - 它应该是)。要了解如何保护它,请查看相关线程How to use Google-Directions-Android library with a restricted API key
这是我使用的工作代码。
import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.maps.model.LatLng;
import org.json.JSONObject;
public class MapsActivity extends FragmentActivity
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
getDirectionsUrl(new LatLng(35.1, -117.9), new LatLng(37.7, -122.4));
private void getDirectionsUrl(LatLng picklatlng, LatLng droplatlng)
if (picklatlng != null && droplatlng != null)
String str_origin = "origin=" + picklatlng.latitude + "," + picklatlng.longitude;
String str_dest = "destination=" + droplatlng.latitude + "," + droplatlng.longitude;
String sensor = "sensor=false";
String parameters = str_origin + "&" + str_dest + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?key=MY_API_KEY&" + parameters;
JsonObjectRequest jsonRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new com.android.volley.Response.Listener // CHANGES HERE
<JSONObject>()
@Override
public void onResponse(JSONObject response)
System.out.println(response.toString());
, new com.android.volley.Response.ErrorListener()
@Override
public void onErrorResponse(VolleyError error)
error.printStackTrace();
);
Volley.newRequestQueue(this).add(jsonRequest);
输出:
"geocoded_waypoints":["geocoder_status":"OK","place_id":"ChIJm_nMTZjSw4ARZA1AAEnxllA","types":["route"],"geocoder_status":"OK","place_id":"Eic3MDMgVHVubmVsIEF2ZSwgQnJpc2JhbmUsIENBIDk0MDA1LCBVU0EiGxIZChQKEglzvTxD1niPgBGTzG36JaRIkxC_BQ","types":["street_address"]],"routes":["bounds":"northeast":"lat":37.6999852,"lng":-117.9000042,"southwest":"lat":35.097047,"lng":-122.4068915,"copyrights":"Map data ©2020 Google","legs":["distance":"text":"355 mi","value":572013,"duration":"text":"5 hours 41 mins","value":20477,"end_address":"703 Tunnel Ave, Brisbane, CA 94005, USA","end_location":"lat":37.6999852,"lng":-122.4003035,"start_address":"Georgia Ave, Edwards, CA 93523, USA","start_location":"lat":35.1006073,"lng":-117.9000042,"steps":["distance":"text":"285 ft","value":87,"duration":"text":"1 min","value":7,"end_location":"lat":35.100593,"lng":-117.900961, [...]
希望这会有所帮助!
【讨论】:
以上是关于Google Map Directions Api v2 无法执行路线/路径请求的主要内容,如果未能解决你的问题,请参考以下文章
Google Maps API [Directions API] 航点限制?
Google Maps API DirectionsService.route 与 Google Maps Directions 不同
如何从 Google Maps Directions Api 获取折线
如何让 Google Maps Directions API 选择正确的机场?