//markerClick事件 @Override public boolean onMarkerClick(Marker marker) { if(marker.equals(myMaker)) return true; final String url = getDirectionsUrl(mMyLatLng, marker.getPosition()); new Thread(new Runnable() { @Override public void run() { String data = getRouteJsonData(url); ParserTask parserTask = new ParserTask(); parserTask.execute(data); } }).start(); return true; } private class ParserTask extends AsyncTask>>> { @Override protected List >> doInBackground(String... jsonData){ JSONObject jObject; List
>> routes = null; try { jObject = new JSONObject(jsonData[0]); DirectionsJSONParser parser = new DirectionsJSONParser(); // Starts parsing data routes = parser.parse(jObject); } catch (Exception e) { e.printStackTrace(); } return routes; } @Override protected void onPostExecute(List
>> result) { ArrayList
points = null; MarkerOptions markerOptions = new MarkerOptions(); PolylineOptions lineOptions = null; // Traversing through all the routes for (int i = 0; i < result.size(); i++) { points = new ArrayList (); lineOptions = new PolylineOptions(); // Fetching i-th route List > path = result.get(i); // Fetching all the points in i-th route for (int j = 0; j < path.size(); j++) { HashMap point = path.get(j); 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(10); //導航路徑寬度 lineOptions.color(0xfff42046); //導航路徑顏色 } if(mPolyline != null) mPolyline.remove(); mPolyline = mGoogleMap.addPolyline(lineOptions); } } public static String getDirectionsUrl(LatLng origin, LatLng dest) { String url=""; String str_origin = "origin=" + origin.latitude + "," + origin.longitude; String str_dest = "destination=" + dest.latitude + "," + dest.longitude; String sensor = "sensor=false"; String mode = "mode=walking"; url = "https://maps.googleapis.com/maps/api/directions/json?" + str_origin + "&" + str_dest + "&" + sensor + "&" + mode; return url; } public static String getRouteJsonData(String strUrl) { String data = ""; InputStream iStream = null; HttpURLConnection urlConnection = null; try { URL url = new URL(strUrl); // Creating an http connection to communicate with url urlConnection = (HttpURLConnection) url.openConnection(); // Connecting to url urlConnection.connect(); // Reading data from url iStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); StringBuffer sb = new StringBuffer(); String line = ""; while ((line = br.readLine()) != null) { sb.append(line); } data = sb.toString(); br.close(); } catch (Exception e) { Log.d("Exception while downloading url", e.toString()); } finally { try { iStream.close(); } catch (IOException e) { e.printStackTrace(); } urlConnection.disconnect(); } return data; }
2014年9月30日 星期二
Android-筆記 GoogleMap 路徑規劃
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言