使用Google Maps Android API v2绘制两点之间的路径 [英] Draw path between two points using Google Maps Android API v2
问题描述
我已经设法使用API V2绘制路径。我已经搜索了很多解决方案,但没有找到任何答案。所以我正在分享它的答案。
首先,我们将获得源点和目的点之间的路线。然后我们将这些属性传递给下面的函数。 这个函数将使我们发送的url获得方向API响应。然后我们将解析这个回应。解析器类是 这个解析器会返回字符串。我们会这样称呼它。 现在我们将把这个字符串发送到drawpath函数。 drawpath函数是 以上代码将在mMap上绘制路径。 decodePoly的代码是 由于方向调用可能需要时间,所以我们将在异步任务中完成所有这些。 我希望这会有所帮助。 Google changed its map API for Android and introduced API V2. The previous codes for drawing path are not working with API V2. I have managed to draw a path with API V2. I had searched a lot for the solution but did not find any answer. So I am sharing its answer. First of all we will get source and destination points between which we have to draw route. Then we will pass these attribute to below function. This function will make the url that we will send to get Direction API response. Then we will parse that response . The parser class is This parser will return us string. We will call it like that. Now we will send this string to our drawpath function. The drawpath function is Above code will draw the path on mMap. The code of decodePoly is As direction call may take time so we will do all this in Asynchronous task.
My Asynchronous task was I hope it will help. 这篇关于使用Google Maps Android API v2绘制两点之间的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
$ b $ pre $ 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);
urlString.append(& key = YOUR_API_KEY);
return urlString.toString();
$ b $ p
$ b
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json =;
//构造函数
public JSONParser(){
}
public String getJSONFromUrl(String url){
//发出HTTP请求
尝试{
// 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();
}
尝试{
BufferedReader reader = new BufferedReader(new InputStreamReader(
is,iso-8859-1),8);
StringBuilder sb = new StringBuilder();
String line = null; ((line = reader.readLine())!= null){
sb.append(line +\\\
);
while
}
json = sb.toString();
is.close();
} catch(Exception e){
Log.e(Buffer Error,Error conversion result+ e.toString());
}
返回json;
$ b
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
public void drawPath(String result){
try {
//将字符串转换为json对象
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray(routes);
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject(overview_polyline);
字符串encodedString = overviewPolylines.getString(points);
列表< LatLng> list = decodePoly(encodedString);
Polyline line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.parseColor(#05b1fb)) // Google地图蓝色
.geodesic(true)
); (int z = 0; z< list.size() - 1; z ++){
LatLng src = list.get(z);
/ *
。
LatLng dest = list.get(z + 1);
Polyline line = mMap.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){
}
}
private List< LatLng> decodePoly(字符串编码){
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 + = 5;
} while(b> = 0x20);
int dlat =((result& 1)!= 0?〜(result>> 1):( result>> 1));
lat + = dlat;
shift = 0;
结果= 0;
do {
b = encoded.charAt(index ++) - 63;
result | =(b& 0x1f)<<转移;
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;
$ b
我的异步任务是
private class connectAsyncTask extends AsyncTask< Void,Void,String> {
private ProgressDialog progressDialog;
字符串网址;
connectAsyncTask(String urlPass){
url = urlPass;
@Override
保护void onPreExecute(){
// TODO自动生成的方法存根
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage(获取路由,请稍候...);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
@Override
protected String doInBackground(Void ... params){
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
返回json;
}
@Override
protected void onPostExecute(String result){
super.onPostExecute(result);
progressDialog.hide();
if(result!= null){
drawPath(result);
}
}
}
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");
urlString.append("&key=YOUR_API_KEY");
return urlString.toString();
}
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
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;
}
}
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
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);
Polyline line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.parseColor("#05b1fb"))//Google maps blue color
.geodesic(true)
);
/*
for(int z = 0; z<list.size()-1;z++){
LatLng src= list.get(z);
LatLng dest= list.get(z+1);
Polyline line = mMap.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) {
}
}
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;
}
private class connectAsyncTask extends AsyncTask<Void, Void, String>{
private ProgressDialog progressDialog;
String url;
connectAsyncTask(String urlPass){
url = urlPass;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
@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);
}
}
}