Vamos fazer uma rota de onde você se encontra para a academia que você escolheu, ao clicar no botão COMO CHEGAR.
Vamos utilizar o Google Maps, outra opção que eu vi é o Mapbox só que não consegui fazer funcionar com essa biblioteca.
Para utilizar o Google Maps você precisar criar um projeto na plataforma do Google para poder gerar uma chave de acesso. (Não sabe criar um projeto? Siga os primeiros passos desse tutorial)
Siga esse tutorial para obter a chave de acesso: Guia rápido: como obter uma Chave de API do Google Maps?
Outra API que devemos ativar é a Direction API, veja o passo 11 desse tutorial.
Agora vamos aos arquivos e veja os códigos:
build.gradle
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
apply plugin: 'com.android.application' //apply plugin: 'kotlin-android' android { compileSdkVersion 30 defaultConfig { applicationId "br.com.micheladrianomedeiros.ondetreinar" minSdkVersion 19 targetSdkVersion 30 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility = 1.8 targetCompatibility = 1.8 } android { buildFeatures{ dataBinding = true viewBinding = true } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation 'com.google.android.material:material:1.2.0' implementation 'androidx.navigation:navigation-fragment:2.3.0' implementation 'androidx.navigation:navigation-ui:2.3.0' testImplementation 'junit:junit:4.13' androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' //gson implementation 'com.google.code.gson:gson:2.8.6' def recyclerview_version = "1.0.0" implementation "androidx.recyclerview:recyclerview:$recyclerview_version" implementation "androidx.recyclerview:recyclerview-selection:$recyclerview_version" implementation 'com.github.bumptech.glide:glide:4.8.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0' implementation 'com.squareup.picasso:picasso:2.71828' //Google Maps implementation 'com.google.android.gms:play-services-maps:17.0.0' implementation 'com.google.android.gms:play-services-location:17.0.0' androidTestImplementation 'androidx.test:runner:1.2.0' } |
activity_como_chegar.xml
Esse arquivo é a tela que mostra o mapa com a rota. Para criar essa tela escolha a activity que já vem preparada para mapas.
1 2 3 4 5 6 7 8 9 |
<?xml version="1.0" encoding="utf-8"?> <fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:map="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/map" android:name="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".mapa.ComoChegar" /> |
AndroidManifest.xml
As seguintes declarações: @string/google_maps_key e @integer/google_play_services_version.
O primeiro está no arquivo google_maps_api.xml.
1 2 3 |
<resources> <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">Coloque aqui a sua chave</string> </resources> |
O segundo está no arquivo values.xml, esse arquivo não fica visível para você, ele está na pasta do gradle.
Pelo que eu lembre esses dois arquivos são gerados automaticamente.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="br.com.micheladrianomedeiros.ondetreinar"> <!-- The ACCESS_COARSE/FINE_LOCATION permissions are not required to use Google Maps Android API v2, but you must specify either coarse or fine location permissions for the "MyLocation" functionality. --> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" android:usesCleartextTraffic="true"> <!-- The API key for Google Maps-based APIs is defined as a string resource. (See the file "res/values/google_maps_api.xml"). Note that the API key is linked to the encryption key used to sign the APK. You need a different API key for each encryption key, including the release key that is used to sign the APK for publishing. You can define the keys for the debug and release targets in src/debug/ and src/release/. --> <meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/google_maps_key" /> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <activity android:name=".mapa.ComoChegar" android:label="@string/title_activity_como_chegar"></activity> <activity android:name=".DetalheActivity" android:label="@string/title_activity_detalhe" android:theme="@style/AppTheme.NoActionBar" /> <activity android:name=".ReviewList" /> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
DetalheActivity.java
Adicionei nesse arquivo a linha public static String ENDERECO_ACADEMIA = null; para ser utilizado no arquivo ComoChegar.java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
package br.com.micheladrianomedeiros.ondetreinar; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import com.squareup.picasso.Picasso; import br.com.micheladrianomedeiros.ondetreinar.adapters.CustomAdapter; import br.com.micheladrianomedeiros.ondetreinar.mapa.ComoChegar; import br.com.micheladrianomedeiros.ondetreinar.model.DetalheAcademia; import br.com.micheladrianomedeiros.ondetreinar.remote.HTTPService; public class DetalheActivity extends AppCompatActivity { private TextView nomeDaAcademia, enderecoAcademia, telefoneAcademia, tipoAcademia, siteAcademia; private ImageView imageView; private RatingBar notaAcademia; private Button comoChegar; public static String ENDERECO_ACADEMIA = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detalhe); nomeDaAcademia = findViewById(R.id.nomeDaAcademia); imageView = findViewById(R.id.imagemDaAcademia); enderecoAcademia = findViewById(R.id.enderecoAcademia); telefoneAcademia = findViewById(R.id.telefoneAcademia); tipoAcademia = findViewById(R.id.tipoDeAcademia); siteAcademia = findViewById(R.id.siteDaAcademia); notaAcademia = findViewById(R.id.notaAcademia); comoChegar = findViewById(R.id.comoChegarAcademia); comoChegar.setOnClickListener(buttonClickListener); nomeDaAcademia.setText(CustomAdapter.ACADEMIA_CIDADE.getNome() + "\n" + CustomAdapter.ACADEMIA_CIDADE.getCidade()); Picasso.get().load(CustomAdapter.ACADEMIA_CIDADE.getThumb()) .resize(100, 100).centerCrop().into(imageView); buscarAcademia(); } private void buscarAcademia() { try { HTTPService service = new HTTPService(); DetalheAcademia detalheAcademia = service .buscarAcademia(CustomAdapter.ACADEMIA_CIDADE.getId()); ENDERECO_ACADEMIA = detalheAcademia.getEndereco(); enderecoAcademia.setText(ENDERECO_ACADEMIA); telefoneAcademia.setText(detalheAcademia.getTelefone()); tipoAcademia.setText(detalheAcademia.getTipoAcademia()); siteAcademia.setText(detalheAcademia.getSite()); notaAcademia.setRating(detalheAcademia.getNota()); } catch (Exception e) { } } private View.OnClickListener buttonClickListener = v -> { switch (v.getId()) { case R.id.comoChegarAcademia: Intent intent = new Intent(this, ComoChegar.class); startActivity(intent); break; case View.NO_ID: default: Log.i("erro", "nada"); break; } }; } |
DirectionParser.java
Esse arquivo coloquei na pasta tools.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
package br.com.micheladrianomedeiros.ondetreinar.tools; import com.google.android.gms.maps.model.LatLng; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class DirectionParser { /** * Receives a JSONObject and returns a list of lists containing latitude and longitude */ public List<List<HashMap<String, String>>> parse(JSONObject jObject) { List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>(); JSONArray jRoutes = null; JSONArray jLegs = null; JSONArray jSteps = null; try { jRoutes = jObject.getJSONArray("routes"); /** Traversing all routes */ for (int i = 0; i < jRoutes.length(); i++) { jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs"); List path = new ArrayList<HashMap<String, String>>(); /** Traversing all legs */ for (int j = 0; j < jLegs.length(); j++) { jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps"); /** Traversing all steps */ for (int k = 0; k < jSteps.length(); k++) { String polyline = ""; polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points"); List<LatLng> list = decodePoly(polyline); /** Traversing all points */ for (int l = 0; l < list.size(); l++) { HashMap<String, String> hm = new HashMap<String, String>(); hm.put("lat", Double.toString(((LatLng) list.get(l)).latitude)); hm.put("lng", Double.toString(((LatLng) list.get(l)).longitude)); path.add(hm); } } routes.add(path); } } } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { } return routes; } 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; } } |
ComoChegar.java
Esse arquivo é o que vai manipular os dados para criar a rota, eu criei uma pasta chamada mapa e coloquei esse arquivo lá.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 |
package br.com.micheladrianomedeiros.ondetreinar.mapa; import androidx.core.app.ActivityCompat; import androidx.fragment.app.FragmentActivity; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.Color; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; 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.tasks.Task; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import br.com.micheladrianomedeiros.ondetreinar.DetalheActivity; import br.com.micheladrianomedeiros.ondetreinar.R; import br.com.micheladrianomedeiros.ondetreinar.tools.DirectionParser; public class ComoChegar extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; private LatLng mOrigin; Location currentLocation; FusedLocationProviderClient fusedLocationProviderClient; private static final int REQUEST_CODE = 101; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_como_chegar); fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this); fetchLocation(); } private void fetchLocation() { if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE); return; } Task<Location> task = fusedLocationProviderClient.getLastLocation(); task.addOnSuccessListener(location -> { if (location != null) { currentLocation = location; SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); assert supportMapFragment != null; supportMapFragment.getMapAsync(ComoChegar.this); mOrigin = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()); } }); } /** * This method will manipulate the Google Map on the main screen */ @Override public void onMapReady(GoogleMap googleMap) { //Google map setup mMap = googleMap; mMap.getUiSettings().setZoomControlsEnabled(true); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } mMap.setMyLocationEnabled(true); mMap.getUiSettings().setMyLocationButtonEnabled(true); // Show marker on the screen and adjust the zoom level mMap.addMarker(new MarkerOptions().position(mOrigin).title("EU")); mMap.addMarker(new MarkerOptions().position(getLocationFromAddress(this)).title("DESTINO")); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mOrigin,15)); new TaskDirectionRequest().execute(buildRequestUrl(mOrigin)); } /** * Create requested url for Direction API to get routes from origin to destination * * @param origin * @return */ private String buildRequestUrl(LatLng origin) { String strOrigin = "origin=" + origin.latitude + "," + origin.longitude; String strDestination = "destination="+ DetalheActivity.ENDERECO_ACADEMIA; String sensor = "sensor=false"; String mode = "mode=driving"; String param = strOrigin + "&" + strDestination + "&" + sensor + "&" + mode; String output = "json"; String APIKEY = getResources().getString(R.string.google_maps_key); String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + param + "&key="+APIKEY; Log.d("TAG", url); return url; } /** * Request direction from Google Direction API * * * @return JSON data routes/direction */ private String requestDirection(String requestedUrl) { String responseString = ""; InputStream inputStream = null; HttpURLConnection httpURLConnection = null; try { URL url = new URL(requestedUrl); httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.connect(); inputStream = httpURLConnection.getInputStream(); InputStreamReader reader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(reader); StringBuffer stringBuffer = new StringBuffer(); String line = ""; while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line); } responseString = stringBuffer.toString(); bufferedReader.close(); reader.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } httpURLConnection.disconnect(); return responseString; } //Get JSON data from Google Direction public class TaskDirectionRequest extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... strings) { String responseString = ""; try { responseString = requestDirection(strings[0]); } catch (Exception e) { e.printStackTrace(); } return responseString; } @Override protected void onPostExecute(String responseString) { super.onPostExecute(responseString); //Json object parsing TaskParseDirection parseResult = new TaskParseDirection(); parseResult.execute(responseString); } } //Parse JSON Object from Google Direction API & display it on Map public class TaskParseDirection extends AsyncTask<String, Void, List<List<HashMap<String, String>>>> { @Override protected List<List<HashMap<String, String>>> doInBackground(String... jsonString) { List<List<HashMap<String, String>>> routes = null; JSONObject jsonObject = null; try { jsonObject = new JSONObject(jsonString[0]); DirectionParser parser = new DirectionParser(); routes = parser.parse(jsonObject); } catch (JSONException e) { e.printStackTrace(); } return routes; } @Override protected void onPostExecute(List<List<HashMap<String, String>>> lists) { super.onPostExecute(lists); ArrayList points = null; PolylineOptions polylineOptions = null; for (List<HashMap<String, String>> path : lists) { points = new ArrayList(); polylineOptions = new PolylineOptions(); for (HashMap<String, String> point : path) { double lat = Double.parseDouble(point.get("lat")); double lon = Double.parseDouble(point.get("lng")); points.add(new LatLng(lat, lon)); } polylineOptions.addAll(points); polylineOptions.width(15f); polylineOptions.color(Color.BLUE); polylineOptions.geodesic(true); } if (polylineOptions != null) { mMap.addPolyline(polylineOptions); } else { Toast.makeText(getApplicationContext(), "Direction not found", Toast.LENGTH_LONG).show(); } } } public LatLng getLocationFromAddress(Context context) { Geocoder coder = new Geocoder(context); List<Address> address; LatLng p1 = null; try { // May throw an IOException address = coder.getFromLocationName(DetalheActivity.ENDERECO_ACADEMIA, 5); if (address == null) { return null; } Address location = address.get(0); p1 = new LatLng(location.getLatitude(), location.getLongitude() ); } catch (IOException ex) { ex.printStackTrace(); } return p1; } } |
Fonte:
https://c1ctech.com/android-googlemap-example-to-draw-route-between-two-locations/
https://www.journaldev.com/13373/android-google-map-drawing-route-two-points
https://www.tutorialspoint.com/how-to-show-current-location-on-a-google-map-on-android
Deixe um comentário