Advertisement
Guest User

Untitled

a guest
Apr 18th, 2014
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.85 KB | None | 0 0
  1. protected void onCreate(Bundle savedInstanceState) {
  2.  
  3. super.onCreate(savedInstanceState);
  4. setContentView(R.layout.activity_main);
  5.  
  6. try {
  7. initilizeMap();
  8.  
  9. tvDistanceDuration = (TextView) findViewById(R.id.tv_distance_time);
  10. // Initializing
  11. markerPoints = new ArrayList<LatLng>();
  12.  
  13. // Getting reference to SupportMapFragment of the activity_main
  14. SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
  15.  
  16. // Getting Map for the SupportMapFragment
  17. googleMap = fm.getMap();
  18.  
  19. // Enable MyLocation Button in the Map
  20. googleMap.setMyLocationEnabled(true);
  21.  
  22. googleMap.setOnMapClickListener(new OnMapClickListener() {
  23.  
  24. public void onMapClick(LatLng point) {
  25. // TODO Auto-generated method stub
  26. // Already two locations
  27. if(markerPoints.size()>1){
  28. markerPoints.clear();
  29. googleMap.clear();
  30. }
  31.  
  32. // Adding new item to the ArrayList
  33. markerPoints.add(point);
  34.  
  35. // Creating MarkerOptions
  36. MarkerOptions options = new MarkerOptions();
  37.  
  38. // Setting the position of the marker
  39. options.position(point);
  40.  
  41. /**
  42. * For the start location, the color of marker is GREEN and
  43. * for the end location, the color of marker is RED.
  44. */
  45. if(markerPoints.size()==1){
  46. options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
  47. }else if(markerPoints.size()==2){
  48. options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
  49. }
  50.  
  51. googleMap.addMarker(options);
  52.  
  53. // Checks, whether start and end locations are captured
  54. if(markerPoints.size() >= 2){
  55. LatLng origin = markerPoints.get(0);
  56. LatLng dest = markerPoints.get(1);
  57.  
  58. // Getting URL to the Google Directions API
  59. String url = getDirectionsUrl(origin, dest);
  60.  
  61. DownloadTask downloadTask = new DownloadTask();
  62.  
  63. // Start downloading json data from Google Directions API
  64. downloadTask.execute(url);
  65. }
  66. }
  67. });
  68.  
  69. //Coding Map
  70.  
  71. googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
  72.  
  73. googleMap.setMyLocationEnabled(true);
  74. googleMap.getUiSettings().setZoomControlsEnabled(false);
  75. googleMap.getUiSettings().setMyLocationButtonEnabled(true);
  76. googleMap.getUiSettings().setCompassEnabled(true);
  77. googleMap.getUiSettings().setRotateGesturesEnabled(true);
  78. googleMap.getUiSettings().setZoomGesturesEnabled(true);
  79. googleMap.getMyLocation();
  80.  
  81. double latitude = -6.941830;
  82. double longitude = 107.628480;
  83.  
  84.  
  85.  
  86. MarkerOptions marker = new MarkerOptions().position(
  87. new LatLng(latitude, longitude))
  88. .title("I'm Here");
  89.  
  90. Log.e("Random", "> " + latitude + ", "
  91. + longitude);
  92.  
  93. marker.icon(BitmapDescriptorFactory
  94. .defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
  95. googleMap.addMarker(marker);
  96.  
  97. //setting zoom level
  98. CameraPosition cameraPosition = new CameraPosition.Builder()
  99. .target(new LatLng(latitude,
  100. longitude)).zoom(16).build();
  101.  
  102. googleMap.animateCamera(CameraUpdateFactory
  103. .newCameraPosition(cameraPosition));
  104.  
  105.  
  106.  
  107. } catch (Exception e) {
  108. e.printStackTrace();
  109. }
  110.  
  111. //Coding Slide atau Drawable
  112.  
  113. mTitle = mDrawerTitle = getTitle();
  114.  
  115. // load slide menu item
  116. navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
  117.  
  118. // ngambil nav drawer icons drawer resources
  119. navMenuIcons = getResources()
  120. .obtainTypedArray(R.array.nav_drawer_icons);
  121.  
  122. mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
  123. mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
  124.  
  125. navDrawerItems = new ArrayList<NavDrawerItem>();
  126.  
  127.  
  128. // Home
  129. navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
  130. // Kereta
  131. navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
  132. // Bis
  133. navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
  134. // Pesawat
  135. navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
  136. // Kapal Laut
  137. navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
  138. // Tempat/Place
  139. navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
  140. // About
  141. navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
  142.  
  143.  
  144. navMenuIcons.recycle();
  145.  
  146. mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
  147.  
  148. // setting the nav drawer list adapter
  149. adapter = new NavDrawerListAdapter(getApplicationContext(),
  150. navDrawerItems);
  151. mDrawerList.setAdapter(adapter);
  152.  
  153. // enabling action bar app icon and behaving it as toggle button
  154. getActionBar().setDisplayHomeAsUpEnabled(true);
  155. getActionBar().setHomeButtonEnabled(true);
  156.  
  157. mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
  158. R.drawable.ic_drawer,
  159. R.string.app_name,
  160. R.string.app_name
  161. ) {
  162. public void onDrawerClosed(View view) {
  163. getActionBar().setTitle(mTitle);
  164. // Buat Show
  165. invalidateOptionsMenu();
  166. }
  167.  
  168. public void onDrawerOpened(View drawerView) {
  169. getActionBar().setTitle(mDrawerTitle);
  170. // Buat Hide
  171. invalidateOptionsMenu();
  172. }
  173. };
  174. mDrawerLayout.setDrawerListener(mDrawerToggle);
  175.  
  176. if (savedInstanceState == null) {
  177. displayView(0);
  178. }
  179.  
  180.  
  181.  
  182. }
  183.  
  184.  
  185. private class SlideMenuClickListener implements
  186. ListView.OnItemClickListener {
  187. @Override
  188. public void onItemClick(AdapterView<?> parent, View view, int position,
  189. long id) {
  190. // Buat Display
  191. displayView(position);
  192. }
  193. }
  194.  
  195. @Override
  196. public boolean onCreateOptionsMenu(Menu menu) {
  197. MenuInflater inflater = getMenuInflater();
  198. inflater.inflate(R.menu.main, menu);
  199.  
  200. return super.onCreateOptionsMenu(menu);
  201. }
  202.  
  203. @Override
  204. public boolean onOptionsItemSelected(MenuItem item) {
  205. if (mDrawerToggle.onOptionsItemSelected(item)) {
  206. return true;
  207. }
  208. switch (item.getItemId()) {
  209. case R.id.action_help:
  210. return true;
  211. case R.id.action_refresh:
  212. return true;
  213. case R.id.action_settings:
  214. return true;
  215. case R.id.action_search:
  216. return true;
  217. default:
  218. return super.onOptionsItemSelected(item);
  219. }
  220. }
  221.  
  222. @Override
  223. public boolean onPrepareOptionsMenu(Menu menu) {
  224. boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
  225. menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
  226. return super.onPrepareOptionsMenu(menu);
  227. }
  228.  
  229. private void displayView(int position) {
  230. Fragment fragment = null;
  231. switch (position) {
  232. case 0:
  233. fragment = new HomeFragment();
  234. break;
  235. case 1:
  236. fragment = new KeretaApiFragment();
  237. break;
  238. case 2:
  239. fragment = new BisFragment();
  240. break;
  241. case 3:
  242. fragment = new PesawatFragment();
  243. break;
  244. case 4:
  245. fragment = new KapalLautFragment();
  246. break;
  247. case 5:
  248. fragment = new PlaceFragment();
  249. break;
  250. case 6:
  251. fragment = new AboutFragment();
  252. break;
  253.  
  254. default:
  255. break;
  256. }
  257.  
  258. if (fragment != null) {
  259. FragmentManager fragmentManager = getFragmentManager();
  260. fragmentManager.beginTransaction()
  261. .replace(R.id.frame_container, fragment).commit();
  262.  
  263. mDrawerList.setItemChecked(position, true);
  264. mDrawerList.setSelection(position);
  265. setTitle(navMenuTitles[position]);
  266. mDrawerLayout.closeDrawer(mDrawerList);
  267. } else {
  268. Log.e("MainActivity", "Gagal Memuat");
  269. }
  270. }
  271.  
  272. @Override
  273. public void setTitle(CharSequence title) {
  274. mTitle = title;
  275. getActionBar().setTitle(mTitle);
  276. }
  277.  
  278. @Override
  279. protected void onPostCreate(Bundle savedInstanceState) {
  280. super.onPostCreate(savedInstanceState);
  281. mDrawerToggle.syncState();
  282. }
  283.  
  284. @Override
  285. public void onConfigurationChanged(Configuration newConfig) {
  286. super.onConfigurationChanged(newConfig);
  287. mDrawerToggle.onConfigurationChanged(newConfig);
  288. }
  289.  
  290.  
  291. @Override
  292. protected void onResume() {
  293. super.onResume();
  294. initilizeMap();
  295. }
  296.  
  297. private void initilizeMap() {
  298. if (googleMap == null) {
  299. googleMap = ((MapFragment) getFragmentManager().findFragmentById(
  300. R.id.map)).getMap();
  301.  
  302. // cek map status, bisa dubuat / tidak
  303. if (googleMap == null) {
  304. Toast.makeText(getApplicationContext(),
  305. "Maaf Maps anda gagal dimuat n"+
  306. "Mungkin karena koneksi anda lelet :)", Toast.LENGTH_SHORT)
  307. .show();
  308. }
  309. }
  310. }
  311.  
  312. private String getDirectionsUrl(LatLng origin,LatLng dest){
  313.  
  314. // Origin of route
  315. String str_origin = "origin="+origin.latitude+","+origin.longitude;
  316.  
  317. // Destination of route
  318. String str_dest = "destination="+dest.latitude+","+dest.longitude;
  319.  
  320. // Sensor enabled
  321. String sensor = "sensor=false";
  322.  
  323. // Building the parameters to the web service
  324. String parameters = str_origin+"&"+str_dest+"&"+sensor;
  325.  
  326. // Output format
  327. String output = "json";
  328.  
  329. // Building the url to the web service
  330. String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
  331.  
  332. return url;
  333. }
  334.  
  335. /** A method to download json data from url */
  336. private String downloadUrl(String strUrl) throws IOException{
  337. String data = "";
  338. InputStream iStream = null;
  339. HttpURLConnection urlConnection = null;
  340. try{
  341. URL url = new URL(strUrl);
  342.  
  343. // Creating an http connection to communicate with url
  344. urlConnection = (HttpURLConnection) url.openConnection();
  345.  
  346. // Connecting to url
  347. urlConnection.connect();
  348.  
  349. // Reading data from url
  350. iStream = urlConnection.getInputStream();
  351.  
  352. BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
  353.  
  354. StringBuffer sb = new StringBuffer();
  355.  
  356. String line = "";
  357. while( ( line = br.readLine()) != null){
  358. sb.append(line);
  359. }
  360.  
  361. data = sb.toString();
  362.  
  363. br.close();
  364.  
  365. }catch(Exception e){
  366. Log.d("Exception while downloading url", e.toString());
  367. }finally{
  368. iStream.close();
  369. urlConnection.disconnect();
  370. }
  371. return data;
  372. }
  373.  
  374. private class DownloadTask extends AsyncTask<String, Void, String>{
  375.  
  376. // Downloading data in non-ui thread
  377. @Override
  378. protected String doInBackground(String... url) {
  379.  
  380. // For storing data from web service
  381. String data = "";
  382.  
  383. try{
  384. // Fetching the data from web service
  385. data = downloadUrl(url[0]);
  386. }catch(Exception e){
  387. Log.d("Background Task",e.toString());
  388. }
  389. return data;
  390. }
  391.  
  392. // Executes in UI thread, after the execution of
  393. // doInBackground()
  394. @Override
  395. protected void onPostExecute(String result) {
  396. super.onPostExecute(result);
  397.  
  398. ParserTask parserTask = new ParserTask();
  399.  
  400. // Invokes the thread for parsing the JSON data
  401. parserTask.execute(result);
  402. }
  403. }
  404.  
  405. private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
  406.  
  407. // Parsing the data in non-ui thread
  408. @Override
  409. protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
  410.  
  411. JSONObject jObject;
  412. List<List<HashMap<String, String>>> routes = null;
  413.  
  414. try{
  415. jObject = new JSONObject(jsonData[0]);
  416. DirectionsJSONParser parser = new DirectionsJSONParser();
  417.  
  418. // Starts parsing data
  419. routes = parser.parse(jObject);
  420. }catch(Exception e){
  421. e.printStackTrace();
  422. }
  423. return routes;
  424. }
  425.  
  426. // Executes in UI thread, after the parsing process
  427. @Override
  428. @SuppressWarnings("unused")
  429. protected void onPostExecute(List<List<HashMap<String, String>>> result) {
  430. ArrayList<LatLng> points = null;
  431. PolylineOptions lineOptions = null;
  432. MarkerOptions markerOptions = new MarkerOptions();
  433. String distance = "";
  434. String duration = "";
  435.  
  436. if(result.size()<1){
  437. Toast.makeText(getBaseContext(), "No Points", Toast.LENGTH_SHORT).show();
  438. return;
  439. }
  440.  
  441. // Traversing through all the routes
  442. for(int i=0;i<result.size();i++){
  443. points = new ArrayList<LatLng>();
  444. lineOptions = new PolylineOptions();
  445.  
  446. // Fetching i-th route
  447. List<HashMap<String, String>> path = result.get(i);
  448.  
  449. // Fetching all the points in i-th route
  450. for(int j=0;j<path.size();j++){
  451. HashMap<String,String> point = path.get(j);
  452.  
  453. if(j==0){ // Get distance from the list
  454. distance = (String)point.get("distance");
  455. continue;
  456. }else if(j==1){ // Get duration from the list
  457. duration = (String)point.get("duration");
  458. continue;
  459. }
  460.  
  461. double lat = Double.parseDouble(point.get("lat"));
  462. double lng = Double.parseDouble(point.get("lng"));
  463. LatLng position = new LatLng(lat, lng);
  464.  
  465. points.add(position);
  466. }
  467.  
  468. // Adding all the points in the route to LineOptions
  469. lineOptions.addAll(points);
  470. lineOptions.width(2);
  471. lineOptions.color(Color.RED);
  472. }
  473.  
  474. tvDistanceDuration.setText("Distance:"+distance + ", Duration:"+duration);
  475.  
  476. // Drawing polyline in the Google Map for the i-th route
  477. googleMap.addPolyline(lineOptions);
  478. }
  479. }
  480.  
  481. initilizeMap();
  482.  
  483. googleMap = ((MapFragment) getFragmentManager().findFragmentById(
  484. R.id.map)).getMap();
  485.  
  486. SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
  487.  
  488. // Getting Map for the SupportMapFragment
  489. googleMap = fm.getMap();
  490.  
  491. private android.support.v4.app.FragmentManager ftManager;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement