gpt4 book ai didi

android - Google Map Directions Api 无法执行路线/路径请求

转载 作者:行者123 更新时间:2023-11-29 01:38:31 26 4
gpt4 key购买 nike

我正在尝试在我的应用程序中实现一项功能,该功能使用 Google Maps API Directions 在 map 中绘制路径(从 A 到 B)。由于某种原因,应用程序似乎甚至无法发出请求。

这是 logcat 报告的内容: enter image description here

这是我用来做这件事的类:

public class DrawPath {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

MainActivity actividadPrincipal;


public DrawPath(MainActivity actividadPrincipal){
this.actividadPrincipal = actividadPrincipal;
}


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;
}

public void drawPath(String result) {

try {
//Tranform the string into a json object
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);

for(int z = 0; z<list.size()-1;z++){
LatLng src= list.get(z);
LatLng dest= list.get(z+1);
Polyline line = actividadPrincipal.googleMap.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude))
.width(2)
.color(Color.BLUE).geodesic(true));
}
}
catch (JSONException e) {

}
}

// Parser Class
public String getJSONFromUrl(String url) {

// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}

json = sb.toString();
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;

}

//First of all we will get source and destination points between which we have to draw route. Then we will pass these attribute to getJSONFromUrl function.
public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin="+Double.toString(sourcelat)+","+Double.toString( sourcelog));// from
urlString.append("&destination="+Double.toString(destlat)+","+Double.toString(destlog));// to
urlString.append("&sensor=false");
urlString.append("&mode=driving");
urlString.append("&alternatives=true");
return urlString.toString();
}
}

改编自此Answer : Draw path between two points using Google Maps Android API v2
现在,我检查了 Directions Api Documentation并且没有发现与此问题相关的任何内容。

我是这样从onCreate底部调用上面的函数的(我还没有设计按钮)

//test
DrawPath dPath = new DrawPath(this);
String path = dPath.makeURL(markers.get(0).marker.getPosition().latitude,
markers.get(0).marker.getPosition().longitude,
markers.get(1).marker.getPosition().latitude,
markers.get(1).marker.getPosition().longitude);
dPath.drawPath(path);

我检查了链接,没有发现任何问题。也许我缺少许可?但在那种情况下它会抛出异常。

我尝试将 http 更改为 https 并按照@3amoura 的建议在请求末尾添加“&key=myApiKey”,但出现了同样的错误。

更新
在修复了一些小问题并对 url 进行硬编码以请求 http://maps.googleapis.com/maps/api/directions/json?origin=Granada&destination=Malaga&sensor=false 之后可以用,所以问题出在makeUrl,肯定是我弄错了

最佳答案

它也返回距离和路线,只需要调用方法drawPath(),

第 1 步。//全局声明这些变量

GoogleMap googleMap;
Polyline line;
Double starting_lat,starting_lng;

第 1 步。//** 在您要绘制路线的地方调用此方法并从此处开始经纬度,

          String urlTopass1 = makeURL(starting_lat,
starting_lng, location.getLatitude(),
location.getLongitude());
new connectAsyncTask(urlTopass1).execute();

//**

第 2 步。

private class connectAsyncTask extends AsyncTask<Void, Void, String> {
String url;
connectAsyncTask(String urlPass) {
url = urlPass;
Log.e("test", " :---- 000 " + url);
}

@Override
protected void onPreExecute() {

super.onPreExecute();

}

@Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
return json;
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// progressDialog.hide();
if (result != null) {
drawPath(result);
}
}
}

第 3 步。

public String makeURL(double sourcelat, double sourcelog, double destlat,
double destlog) {
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append(Double.toString(sourcelat));
urlString.append(",");
urlString.append(Double.toString(sourcelog));
urlString.append("&destination=");// to
urlString.append(Double.toString(destlat));
urlString.append(",");
urlString.append(Double.toString(destlog));
urlString.append("&sensor=false&mode=driving&alternatives=true");
return urlString.toString();
}

public class JSONParser {

InputStream is = null;
JSONObject jObj = null;
String json = "";

// constructor
public JSONParser() {
}

public String getJSONFromUrl(String url) {

// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}

json = sb.toString();
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;

}
}

第 4 步。

public void drawPath(String result) {
try {

if (line != null) {
Log.i("removing line", "removed");
googleMap.clear();
}

googleMap.addMarker(new MarkerOptions().position(passLatLng).icon(
BitmapDescriptorFactory.defaultMarker()));
marer= googleMap
.addMarker(new MarkerOptions().position(driverLatLng).icon(
BitmapDescriptorFactory
.fromResource(R.drawable.icon)));
try {

final JSONObject json = new JSONObject(result);

Log.e("test", "json :p== " + json);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
Log.e("test", "routes :== " + routes);

JSONArray newTempARr = routes.getJSONArray("legs");
JSONObject newDisTimeOb = newTempARr.getJSONObject(0);
Log.e("test", "newDisTimeOb :== " + newDisTimeOb);

JSONObject distOb = newDisTimeOb.getJSONObject("distance");

String tempDist[] = distOb.getString("text").toString()
.split(" ");

double tempDoubleDist = Double.valueOf(tempDist[0].replace(",",
""));
totalKm = String.valueOf(tempDoubleDist);

int dist = (int) tempDoubleDist;

JSONObject overviewPolylines = routes
.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);

PolylineOptions options = new PolylineOptions().width(5)
.color(Color.BLUE).geodesic(true);
for (int z = 0; z < list.size(); z++) {
LatLng point = list.get(z);
options.add(point);
}
line = googleMap.addPolyline(options);
Log.e("checking LatLng of pass bef moveCamera", ""
+ passLatLng.latitude + "," + passLatLng.longitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(passLatLng));
if (dist > 2 && dist <= 5) {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(13.0f));
mapZoomLevel = 12;
} else if (dist > 5 && dist <= 10) {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f));
mapZoomLevel = 11;
} else if (dist > 10 && dist <= 20) {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(11.0f));
mapZoomLevel = 11;
} else if (dist > 20 && dist <= 40) {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(10.0f));
mapZoomLevel = 10;
} else if (dist > 40 && dist < 100) {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(9.0f));
mapZoomLevel = 9;
} else if (dist > 100 && dist < 200) {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(8.0f));
mapZoomLevel = 8;
} else if (dist > 200 && dist < 400) {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(7.0f));
mapZoomLevel = 7;
} else if (dist > 400 && dist < 700) {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(6.0f));
mapZoomLevel = 7;
} else if (dist > 700 && dist < 1000) {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(5.0f));
mapZoomLevel = 6;
} else if (dist > 1000) {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(4.0f));
mapZoomLevel = 5;
} else {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(14.0f));
mapZoomLevel = 14;
}

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

第 5 步。

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;
}

关于android - Google Map Directions Api 无法执行路线/路径请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26350528/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com