Advertisement
Guest User

Untitled

a guest
Oct 21st, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.76 KB | None | 0 0
  1. package cs.ut.ee.homework4_3;
  2.  
  3. import android.Manifest;
  4. import android.content.pm.PackageManager;
  5. import android.graphics.Color;
  6. import android.location.Address;
  7. import android.location.Geocoder;
  8. import android.location.Location;
  9. import android.support.annotation.NonNull;
  10. import android.support.v4.app.ActivityCompat;
  11. import android.support.v4.app.FragmentActivity;
  12. import android.os.Bundle;
  13. import android.support.v4.content.ContextCompat;
  14. import android.util.Log;
  15. import android.widget.Toast;
  16.  
  17. import com.google.android.gms.maps.CameraUpdateFactory;
  18. import com.google.android.gms.maps.GoogleMap;
  19. import com.google.android.gms.maps.OnMapReadyCallback;
  20. import com.google.android.gms.maps.SupportMapFragment;
  21. import com.google.android.gms.maps.model.LatLng;
  22. import com.google.android.gms.maps.model.MarkerOptions;
  23. import com.google.android.gms.maps.model.PolylineOptions;
  24. import com.google.android.gms.maps.model.TileOverlay;
  25. import com.google.android.gms.maps.model.TileOverlayOptions;
  26. import com.google.android.gms.maps.model.TileProvider;
  27. import com.google.android.gms.maps.model.UrlTileProvider;
  28. import com.google.maps.DirectionsApi;
  29. import com.google.maps.DirectionsApiRequest;
  30. import com.google.maps.GeoApiContext;
  31. import com.google.maps.model.DirectionsLeg;
  32. import com.google.maps.model.DirectionsResult;
  33. import com.google.maps.model.DirectionsRoute;
  34. import com.google.maps.model.DirectionsStep;
  35. import com.google.maps.model.EncodedPolyline;
  36.  
  37. import java.io.IOException;
  38. import java.net.MalformedURLException;
  39. import java.net.URL;
  40. import java.util.ArrayList;
  41. import java.util.List;
  42. import java.util.Locale;
  43.  
  44. public class MapsActivity extends FragmentActivity implements
  45.         OnMapReadyCallback, GoogleMap.OnMyLocationButtonClickListener,
  46.         GoogleMap.OnMyLocationClickListener {
  47.     private LatLng tartu = new LatLng(58.378300, 26.715509);
  48.  
  49.     private GoogleMap mMap;
  50.     private String TAG = "tööta";
  51.  
  52.     @Override
  53.     protected void onCreate(Bundle savedInstanceState) {
  54.         super.onCreate(savedInstanceState);
  55.         setContentView(R.layout.activity_maps);
  56.         // Obtain the SupportMapFragment and get notified when the map is ready to be used.
  57.         SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
  58.                 .findFragmentById(R.id.map);
  59.         mapFragment.getMapAsync(this);
  60.     }
  61.  
  62.  
  63.     /**
  64.      * Manipulates the map once available.
  65.      * This callback is triggered when the map is ready to be used.
  66.      * This is where we can add markers or lines, add listeners or move the camera. In this case,
  67.      * we just add a marker near Sydney, Australia.
  68.      * If Google Play services is not installed on the device, the user will be prompted to install
  69.      * it inside the SupportMapFragment. This method will only be triggered once the user has
  70.      * installed Google Play services and returned to the app.
  71.      */
  72.     @Override
  73.     public void onMapReady(GoogleMap googleMap) {
  74.         mMap = googleMap;
  75.         mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
  76.  
  77.         // Add a marker in Tartu and move the camera
  78.         mMap.addMarker(new MarkerOptions().position(tartu).title("Marker in Tartu"));
  79.         mMap.moveCamera(CameraUpdateFactory.newLatLng(tartu));
  80.         mMap.moveCamera(CameraUpdateFactory.zoomTo(14));
  81.  
  82.         //Check permission
  83.         {if(checkPermission())
  84.             mMap.setMyLocationEnabled(true);
  85.         else askPermission();}
  86.  
  87.         mMap.setOnMyLocationButtonClickListener(this);
  88.         mMap.setOnMyLocationClickListener(this);
  89.  
  90.  
  91.         //Define list to get all latlng for the route
  92.         List<LatLng> path = new ArrayList<>();
  93.  
  94.  
  95.         //Execute Directions API request
  96.         GeoApiContext context = new GeoApiContext.Builder()
  97.                 .apiKey("AIzaSyDKum8HxeQrFR1eyW7ZSpkIBtLqZdKl9xA")
  98.                 .build();
  99.         DirectionsApiRequest req = DirectionsApi.getDirections(context, "58.367649,25.595329", "58.378300,26.715509");
  100.         try {
  101.             DirectionsResult res = req.await();
  102.  
  103.             //Loop through le   gs and steps to get encoded polylines of each step
  104.             if (res.routes != null && res.routes.length > 0) {
  105.                 DirectionsRoute route = res.routes[0];
  106.  
  107.                 if (route.legs !=null) {
  108.                     for(int i=0; i<route.legs.length; i++) {
  109.                         DirectionsLeg leg = route.legs[i];
  110.                         if (leg.steps != null) {
  111.                             for (int j=0; j<leg.steps.length;j++){
  112.                                 DirectionsStep step = leg.steps[j];
  113.                                 if (step.steps != null && step.steps.length >0) {
  114.                                     for (int k=0; k<step.steps.length;k++){
  115.                                         DirectionsStep step1 = step.steps[k];
  116.                                         EncodedPolyline points1 = step1.polyline;
  117.                                         if (points1 != null) {
  118.                                             //Decode polyline and add points to list of route coordinates
  119.                                             List<com.google.maps.model.LatLng> coords1 = points1.decodePath();
  120.                                             for (com.google.maps.model.LatLng coord1 : coords1) {
  121.                                                 path.add(new LatLng(coord1.lat, coord1.lng));
  122.                                             }
  123.                                         }
  124.                                     }
  125.                                 } else {
  126.                                     EncodedPolyline points = step.polyline;
  127.                                     if (points != null) {
  128.                                         //Decode polyline and add points to list of route coordinates
  129.                                         List<com.google.maps.model.LatLng> coords = points.decodePath();
  130.                                         for (com.google.maps.model.LatLng coord : coords) {
  131.                                             path.add(new LatLng(coord.lat, coord.lng));
  132.                                         }
  133.                                     }
  134.                                 }
  135.                             }
  136.                         }
  137.                     }
  138.                 }
  139.             }
  140.         } catch(Exception ex) {
  141.             Log.e(TAG, ex.getLocalizedMessage());
  142.         }
  143.  
  144.         //Draw the polyline
  145.         if (path.size() > 0) {
  146.             PolylineOptions opts = new PolylineOptions().addAll(path).color(Color.BLUE).width(5);
  147.             mMap.addPolyline(opts);
  148.         }
  149.  
  150.         mMap.getUiSettings().setZoomControlsEnabled(true);
  151.  
  152.         mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(tartu, 6));
  153.  
  154.  
  155.  
  156.         TileProvider tileProvider = new UrlTileProvider(256, 256) {
  157.             @Override
  158.             public URL getTileUrl(int x, int y, int zoom) {
  159.  
  160.                 /* Define the URL pattern for the tile images */
  161.                 String s = String.format("http://tiles.maaamet.ee/tm/tms/1.0.0/kaart@GMC/%d/%d/%d.png",
  162.                         zoom, x, (1 << zoom) - 1 - y);
  163.  
  164.                 if (!checkTileExists(x, y, zoom)) {
  165.                     return null;
  166.                 }
  167.  
  168.                 try {
  169.                     return new URL(s);
  170.                 } catch (MalformedURLException e) {
  171.                     throw new AssertionError(e);
  172.                 }
  173.  
  174.             }
  175.  
  176.  
  177.             /*
  178.              * Check that the tile server supports the requested x, y and zoom.
  179.              * Complete this stub according to the tile range you support.
  180.              * If you support a limited range of tiles at different zoom levels, then you
  181.              * need to define the supported x, y range at each zoom level.
  182.              */
  183.             private boolean checkTileExists(int x, int y, int zoom) {
  184.                 int minZoom = 12;
  185.                 int maxZoom = 18;
  186.  
  187.                 if ((zoom < minZoom || zoom > maxZoom)) {
  188.                     return false;
  189.                 }
  190.  
  191.                 return true;
  192.             }
  193.         };
  194.         TileOverlay tileOverlay = mMap.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
  195.  
  196.  
  197.  
  198.  
  199.  
  200.  
  201.     }
  202.  
  203.     @Override
  204.     public boolean onMyLocationButtonClick() {
  205.         Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
  206.         return false;
  207.     }
  208.  
  209.     @Override
  210.     public void onMyLocationClick(@NonNull Location location) {
  211.         Geocoder geocoder = new Geocoder(this, Locale.JAPANESE);
  212.  
  213.         try {
  214.             List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
  215.  
  216.             if (addresses.size() > 0) {
  217.                 Address fetchedAddress = addresses.get(0);
  218.                 StringBuilder strAddress = new StringBuilder();
  219.                 for (int i = 0; i <= fetchedAddress.getMaxAddressLineIndex(); i++) {
  220.                     strAddress.append(fetchedAddress.getAddressLine(i)).append(" ");
  221.                 }
  222.  
  223.                 Toast.makeText(this, "Current location:\n" + strAddress.toString(), Toast.LENGTH_LONG).show();
  224.  
  225.             } else {
  226.                 Toast.makeText(this, "Current location (No address):\n" + location, Toast.LENGTH_LONG).show();
  227.             }
  228.  
  229.         } catch (IOException e) {
  230.             e.printStackTrace();
  231.             Toast.makeText(this, "Current location (Ex):\n" + location, Toast.LENGTH_LONG).show();
  232.         }
  233.  
  234.     }
  235.  
  236.     // Check for permission to access Location
  237.     private boolean checkPermission() {
  238.         Log.d(TAG, "checkPermission()");
  239.         // Ask for permission if it wasn't granted yet
  240.         return (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
  241.                 == PackageManager.PERMISSION_GRANTED );
  242.     }
  243.     // Asks for permission
  244.     private void askPermission() {
  245.         Log.d(TAG, "askPermission()");
  246.         ActivityCompat.requestPermissions(
  247.                 this,
  248.                 new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
  249.                 1
  250.         );
  251.     }
  252.  
  253.     @Override
  254.     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  255.         Log.d(TAG, "onRequestPermissionsResult()");
  256.         super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  257.         switch ( requestCode ) {
  258.             case 1: {
  259.                 if ( grantResults.length > 0
  260.                         && grantResults[0] == PackageManager.PERMISSION_GRANTED ){
  261.                     // Permission granted
  262.                     if(checkPermission())
  263.                         mMap.setMyLocationEnabled(true);
  264.  
  265.                 } else {
  266.                     // Permission denied
  267.  
  268.                 }
  269.                 break;
  270.             }
  271.         }
  272.     }
  273. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement