Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package cs.ut.ee.homework4_3;
- import android.Manifest;
- import android.content.pm.PackageManager;
- import android.graphics.Color;
- import android.location.Address;
- import android.location.Geocoder;
- import android.location.Location;
- import android.support.annotation.NonNull;
- import android.support.v4.app.ActivityCompat;
- import android.support.v4.app.FragmentActivity;
- import android.os.Bundle;
- import android.support.v4.content.ContextCompat;
- import android.util.Log;
- import android.widget.Toast;
- import com.google.android.gms.maps.CameraUpdateFactory;
- import com.google.android.gms.maps.GoogleMap;
- import com.google.android.gms.maps.OnMapReadyCallback;
- import com.google.android.gms.maps.SupportMapFragment;
- import com.google.android.gms.maps.model.LatLng;
- import com.google.android.gms.maps.model.MarkerOptions;
- import com.google.android.gms.maps.model.PolylineOptions;
- import com.google.android.gms.maps.model.TileOverlay;
- import com.google.android.gms.maps.model.TileOverlayOptions;
- import com.google.android.gms.maps.model.TileProvider;
- import com.google.android.gms.maps.model.UrlTileProvider;
- import com.google.maps.DirectionsApi;
- import com.google.maps.DirectionsApiRequest;
- import com.google.maps.GeoApiContext;
- import com.google.maps.model.DirectionsLeg;
- import com.google.maps.model.DirectionsResult;
- import com.google.maps.model.DirectionsRoute;
- import com.google.maps.model.DirectionsStep;
- import com.google.maps.model.EncodedPolyline;
- import java.io.IOException;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Locale;
- public class MapsActivity extends FragmentActivity implements
- OnMapReadyCallback, GoogleMap.OnMyLocationButtonClickListener,
- GoogleMap.OnMyLocationClickListener {
- private LatLng tartu = new LatLng(58.378300, 26.715509);
- private GoogleMap mMap;
- private String TAG = "tööta";
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_maps);
- // Obtain the SupportMapFragment and get notified when the map is ready to be used.
- SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
- .findFragmentById(R.id.map);
- mapFragment.getMapAsync(this);
- }
- /**
- * Manipulates the map once available.
- * This callback is triggered when the map is ready to be used.
- * This is where we can add markers or lines, add listeners or move the camera. In this case,
- * we just add a marker near Sydney, Australia.
- * If Google Play services is not installed on the device, the user will be prompted to install
- * it inside the SupportMapFragment. This method will only be triggered once the user has
- * installed Google Play services and returned to the app.
- */
- @Override
- public void onMapReady(GoogleMap googleMap) {
- mMap = googleMap;
- mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
- // Add a marker in Tartu and move the camera
- mMap.addMarker(new MarkerOptions().position(tartu).title("Marker in Tartu"));
- mMap.moveCamera(CameraUpdateFactory.newLatLng(tartu));
- mMap.moveCamera(CameraUpdateFactory.zoomTo(14));
- //Check permission
- {if(checkPermission())
- mMap.setMyLocationEnabled(true);
- else askPermission();}
- mMap.setOnMyLocationButtonClickListener(this);
- mMap.setOnMyLocationClickListener(this);
- //Define list to get all latlng for the route
- List<LatLng> path = new ArrayList<>();
- //Execute Directions API request
- GeoApiContext context = new GeoApiContext.Builder()
- .apiKey("AIzaSyDKum8HxeQrFR1eyW7ZSpkIBtLqZdKl9xA")
- .build();
- DirectionsApiRequest req = DirectionsApi.getDirections(context, "58.367649,25.595329", "58.378300,26.715509");
- try {
- DirectionsResult res = req.await();
- //Loop through le gs and steps to get encoded polylines of each step
- if (res.routes != null && res.routes.length > 0) {
- DirectionsRoute route = res.routes[0];
- if (route.legs !=null) {
- for(int i=0; i<route.legs.length; i++) {
- DirectionsLeg leg = route.legs[i];
- if (leg.steps != null) {
- for (int j=0; j<leg.steps.length;j++){
- DirectionsStep step = leg.steps[j];
- if (step.steps != null && step.steps.length >0) {
- for (int k=0; k<step.steps.length;k++){
- DirectionsStep step1 = step.steps[k];
- EncodedPolyline points1 = step1.polyline;
- if (points1 != null) {
- //Decode polyline and add points to list of route coordinates
- List<com.google.maps.model.LatLng> coords1 = points1.decodePath();
- for (com.google.maps.model.LatLng coord1 : coords1) {
- path.add(new LatLng(coord1.lat, coord1.lng));
- }
- }
- }
- } else {
- EncodedPolyline points = step.polyline;
- if (points != null) {
- //Decode polyline and add points to list of route coordinates
- List<com.google.maps.model.LatLng> coords = points.decodePath();
- for (com.google.maps.model.LatLng coord : coords) {
- path.add(new LatLng(coord.lat, coord.lng));
- }
- }
- }
- }
- }
- }
- }
- }
- } catch(Exception ex) {
- Log.e(TAG, ex.getLocalizedMessage());
- }
- //Draw the polyline
- if (path.size() > 0) {
- PolylineOptions opts = new PolylineOptions().addAll(path).color(Color.BLUE).width(5);
- mMap.addPolyline(opts);
- }
- mMap.getUiSettings().setZoomControlsEnabled(true);
- mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(tartu, 6));
- TileProvider tileProvider = new UrlTileProvider(256, 256) {
- @Override
- public URL getTileUrl(int x, int y, int zoom) {
- /* Define the URL pattern for the tile images */
- String s = String.format("http://tiles.maaamet.ee/tm/tms/1.0.0/kaart@GMC/%d/%d/%d.png",
- zoom, x, (1 << zoom) - 1 - y);
- if (!checkTileExists(x, y, zoom)) {
- return null;
- }
- try {
- return new URL(s);
- } catch (MalformedURLException e) {
- throw new AssertionError(e);
- }
- }
- /*
- * Check that the tile server supports the requested x, y and zoom.
- * Complete this stub according to the tile range you support.
- * If you support a limited range of tiles at different zoom levels, then you
- * need to define the supported x, y range at each zoom level.
- */
- private boolean checkTileExists(int x, int y, int zoom) {
- int minZoom = 12;
- int maxZoom = 18;
- if ((zoom < minZoom || zoom > maxZoom)) {
- return false;
- }
- return true;
- }
- };
- TileOverlay tileOverlay = mMap.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
- }
- @Override
- public boolean onMyLocationButtonClick() {
- Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
- return false;
- }
- @Override
- public void onMyLocationClick(@NonNull Location location) {
- Geocoder geocoder = new Geocoder(this, Locale.JAPANESE);
- try {
- List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
- if (addresses.size() > 0) {
- Address fetchedAddress = addresses.get(0);
- StringBuilder strAddress = new StringBuilder();
- for (int i = 0; i <= fetchedAddress.getMaxAddressLineIndex(); i++) {
- strAddress.append(fetchedAddress.getAddressLine(i)).append(" ");
- }
- Toast.makeText(this, "Current location:\n" + strAddress.toString(), Toast.LENGTH_LONG).show();
- } else {
- Toast.makeText(this, "Current location (No address):\n" + location, Toast.LENGTH_LONG).show();
- }
- } catch (IOException e) {
- e.printStackTrace();
- Toast.makeText(this, "Current location (Ex):\n" + location, Toast.LENGTH_LONG).show();
- }
- }
- // Check for permission to access Location
- private boolean checkPermission() {
- Log.d(TAG, "checkPermission()");
- // Ask for permission if it wasn't granted yet
- return (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
- == PackageManager.PERMISSION_GRANTED );
- }
- // Asks for permission
- private void askPermission() {
- Log.d(TAG, "askPermission()");
- ActivityCompat.requestPermissions(
- this,
- new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
- 1
- );
- }
- @Override
- public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
- Log.d(TAG, "onRequestPermissionsResult()");
- super.onRequestPermissionsResult(requestCode, permissions, grantResults);
- switch ( requestCode ) {
- case 1: {
- if ( grantResults.length > 0
- && grantResults[0] == PackageManager.PERMISSION_GRANTED ){
- // Permission granted
- if(checkPermission())
- mMap.setMyLocationEnabled(true);
- } else {
- // Permission denied
- }
- break;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement