├── LearnGoogleAPI.iml
├── app
├── .gitignore
├── app.iml
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── khilman
│ │ └── www
│ │ └── learngoogleapi
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── khilman
│ │ │ └── www
│ │ │ └── learngoogleapi
│ │ │ ├── DirectionActivity.java
│ │ │ ├── MainActivity.java
│ │ │ ├── OjekActivity.java
│ │ │ ├── PlaceAutoCompleteActivity.java
│ │ │ ├── network
│ │ │ ├── ApiServices.java
│ │ │ └── InitLibrary.java
│ │ │ └── response
│ │ │ ├── Bounds.java
│ │ │ ├── Distance.java
│ │ │ ├── Duration.java
│ │ │ ├── EndLocation.java
│ │ │ ├── GeocodedWaypointsItem.java
│ │ │ ├── LegsItem.java
│ │ │ ├── Northeast.java
│ │ │ ├── OverviewPolyline.java
│ │ │ ├── Polyline.java
│ │ │ ├── ResponseRoute.java
│ │ │ ├── RoutesItem.java
│ │ │ ├── Southwest.java
│ │ │ ├── StartLocation.java
│ │ │ └── StepsItem.java
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ ├── activity_direction.xml
│ │ ├── activity_main.xml
│ │ ├── activity_ojek.xml
│ │ └── activity_place_auto_complete.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── khilman
│ └── www
│ └── learngoogleapi
│ └── ExampleUnitTest.java
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── local.properties
└── settings.gradle
/LearnGoogleAPI.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/app.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 | generateDebugSources
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 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 26
5 | defaultConfig {
6 | applicationId "com.khilman.www.learngoogleapi"
7 | minSdkVersion 16
8 | targetSdkVersion 26
9 | versionCode 1
10 | versionName "1.0"
11 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | }
20 |
21 | dependencies {
22 | implementation fileTree(dir: 'libs', include: ['*.jar'])
23 | implementation 'com.android.support:appcompat-v7:26.1.0'
24 | implementation 'com.android.support.constraint:constraint-layout:1.0.2'
25 | testImplementation 'junit:junit:4.12'
26 | androidTestImplementation 'com.android.support.test:runner:1.0.1'
27 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
28 | // Google MAPS
29 | implementation 'com.google.android.gms:play-services-maps:11.8.0'
30 |
31 | // Auto Complete Place & location
32 | implementation 'com.google.android.gms:play-services-places:11.8.0'
33 | implementation 'com.google.android.gms:play-services-location:11.8.0'
34 |
35 | // Maps Utils
36 | compile 'com.google.maps.android:android-maps-utils:0.4+'
37 |
38 | // Retrofit
39 | compile 'com.squareup.retrofit2:retrofit:2.3.0'
40 | compile 'com.squareup.retrofit2:converter-gson:2.3.0'
41 | }
42 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/khilman/www/learngoogleapi/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.khilman.www.learngoogleapi;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumented test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.khilman.www.learngoogleapi", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
16 |
17 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/app/src/main/java/com/khilman/www/learngoogleapi/DirectionActivity.java:
--------------------------------------------------------------------------------
1 | package com.khilman.www.learngoogleapi;
2 |
3 | import android.graphics.Color;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.os.Bundle;
6 | import android.widget.TextView;
7 |
8 | import com.google.android.gms.maps.CameraUpdate;
9 | import com.google.android.gms.maps.CameraUpdateFactory;
10 | import com.google.android.gms.maps.GoogleMap;
11 | import com.google.android.gms.maps.OnMapReadyCallback;
12 | import com.google.android.gms.maps.SupportMapFragment;
13 | import com.google.android.gms.maps.model.LatLng;
14 | import com.google.android.gms.maps.model.LatLngBounds;
15 | import com.google.android.gms.maps.model.MarkerOptions;
16 | import com.google.android.gms.maps.model.PolylineOptions;
17 | import com.google.maps.android.PolyUtil;
18 | import com.khilman.www.learngoogleapi.network.ApiServices;
19 | import com.khilman.www.learngoogleapi.network.InitLibrary;
20 | import com.khilman.www.learngoogleapi.response.Distance;
21 | import com.khilman.www.learngoogleapi.response.Duration;
22 | import com.khilman.www.learngoogleapi.response.LegsItem;
23 | import com.khilman.www.learngoogleapi.response.ResponseRoute;
24 |
25 | import java.util.List;
26 |
27 | import retrofit2.Call;
28 | import retrofit2.Callback;
29 | import retrofit2.Response;
30 |
31 | public class DirectionActivity extends AppCompatActivity implements OnMapReadyCallback {
32 | private GoogleMap mMap;
33 |
34 | private String API_KEY = "AIzaSyBe9P-itehQgH5BG7ox5vizpv5E1iGLMhg";
35 |
36 | private LatLng pickUpLatLng = new LatLng(-6.175110, 106.865039); // Jakarta
37 | private LatLng locationLatLng = new LatLng(-6.197301,106.795951); // Cirebon
38 |
39 | private TextView tvStartAddress, tvEndAddress, tvDuration, tvDistance;
40 | @Override
41 | protected void onCreate(Bundle savedInstanceState) {
42 | super.onCreate(savedInstanceState);
43 | setContentView(R.layout.activity_direction);
44 | // Maps
45 | SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
46 | .findFragmentById(R.id.map);
47 | mapFragment.getMapAsync(this);
48 | // Set Title bar
49 | getSupportActionBar().setTitle("Direction Maps API");
50 | // Inisialisasi Widget
51 | widgetInit();
52 | // jalankan method
53 | actionRoute();
54 | }
55 |
56 | private void widgetInit() {
57 | tvStartAddress = findViewById(R.id.tvStartAddress);
58 | tvEndAddress = findViewById(R.id.tvEndAddress);
59 | tvDuration = findViewById(R.id.tvDuration);
60 | tvDistance = findViewById(R.id.tvDistance);
61 | }
62 |
63 | private void actionRoute() {
64 | String lokasiAwal = pickUpLatLng.latitude + "," + pickUpLatLng.longitude;
65 | String lokasiAkhir = locationLatLng.latitude + "," + locationLatLng.longitude;
66 |
67 | // Panggil Retrofit
68 | ApiServices api = InitLibrary.getInstance();
69 | // Siapkan request
70 | Call routeRequest = api.request_route(lokasiAwal, lokasiAkhir, API_KEY);
71 | // kirim request
72 | routeRequest.enqueue(new Callback() {
73 | @Override
74 | public void onResponse(Call call, Response response) {
75 |
76 | if (response.isSuccessful()){
77 | // tampung response ke variable
78 | ResponseRoute dataDirection = response.body();
79 |
80 | LegsItem dataLegs = dataDirection.getRoutes().get(0).getLegs().get(0);
81 |
82 | // Dapatkan garis polyline
83 | String polylinePoint = dataDirection.getRoutes().get(0).getOverviewPolyline().getPoints();
84 | // Decode
85 | List decodePath = PolyUtil.decode(polylinePoint);
86 | // Gambar garis ke maps
87 | mMap.addPolyline(new PolylineOptions().addAll(decodePath)
88 | .width(8f).color(Color.argb(255, 56, 167, 252)))
89 | .setGeodesic(true);
90 |
91 | // Tambah Marker
92 | mMap.addMarker(new MarkerOptions().position(pickUpLatLng).title("Lokasi Awal"));
93 | mMap.addMarker(new MarkerOptions().position(locationLatLng).title("Lokasi Akhir"));
94 | // Dapatkan jarak dan waktu
95 | Distance dataDistance = dataLegs.getDistance();
96 | Duration dataDuration = dataLegs.getDuration();
97 |
98 | // Set Nilai Ke Widget
99 | tvStartAddress.setText("start location : " + dataLegs.getStartAddress().toString());
100 | tvEndAddress.setText("end location : " + dataLegs.getEndAddress().toString());
101 |
102 | tvDistance.setText("distance : " + dataDistance.getText() + " (" + dataDistance.getValue() + ")");
103 | tvDuration.setText("duration : " + dataDuration.getText() + " (" + dataDuration.getValue() + ")");
104 | /** START
105 | * Logic untuk membuat layar berada ditengah2 dua koordinat
106 | */
107 |
108 | LatLngBounds.Builder latLongBuilder = new LatLngBounds.Builder();
109 | latLongBuilder.include(pickUpLatLng);
110 | latLongBuilder.include(locationLatLng);
111 |
112 | // Bounds Coordinata
113 | LatLngBounds bounds = latLongBuilder.build();
114 |
115 | int width = getResources().getDisplayMetrics().widthPixels;
116 | int height = getResources().getDisplayMetrics().heightPixels;
117 | int paddingMap = (int) (width * 0.2); //jarak dari
118 | CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, paddingMap);
119 | mMap.animateCamera(cu);
120 |
121 | /** END
122 | * Logic untuk membuat layar berada ditengah2 dua koordinat
123 | */
124 |
125 | }
126 | }
127 |
128 | @Override
129 | public void onFailure(Call call, Throwable t) {
130 | t.printStackTrace();
131 | }
132 | });
133 | }
134 |
135 |
136 | @Override
137 | public void onMapReady(GoogleMap googleMap) {
138 | mMap = googleMap;
139 | }
140 | }
141 |
--------------------------------------------------------------------------------
/app/src/main/java/com/khilman/www/learngoogleapi/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.khilman.www.learngoogleapi;
2 |
3 | import android.Manifest;
4 | import android.content.Intent;
5 | import android.content.pm.PackageManager;
6 | import android.support.v4.app.ActivityCompat;
7 | import android.support.v4.content.ContextCompat;
8 | import android.support.v7.app.AppCompatActivity;
9 | import android.os.Bundle;
10 | import android.view.View;
11 | import android.widget.Toast;
12 |
13 | public class MainActivity extends AppCompatActivity {
14 |
15 | @Override
16 | protected void onCreate(Bundle savedInstanceState) {
17 | super.onCreate(savedInstanceState);
18 | setContentView(R.layout.activity_main);
19 |
20 | // Here, thisActivity is the current activity
21 | if (ContextCompat.checkSelfPermission(this,
22 | Manifest.permission.ACCESS_FINE_LOCATION)
23 | != PackageManager.PERMISSION_GRANTED) {
24 |
25 | // Permission is not granted
26 | if (ActivityCompat.shouldShowRequestPermissionRationale(this,
27 | Manifest.permission.ACCESS_FINE_LOCATION)) {
28 | Toast.makeText(this, "Membutuhkan Izin Lokasi", Toast.LENGTH_SHORT).show();
29 | } else {
30 |
31 | // No explanation needed; request the permission
32 | ActivityCompat.requestPermissions(this,
33 | new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
34 | 1);
35 | }
36 | } else {
37 | // Permission has already been granted
38 | Toast.makeText(this, "Izin Lokasi diberikan", Toast.LENGTH_SHORT).show();
39 | }
40 | }
41 |
42 | public void openAutoPlace(View view) {
43 | startActivity(new Intent(this, PlaceAutoCompleteActivity.class));
44 | }
45 |
46 | public void openDirectionMap(View view) {
47 | startActivity(new Intent(this, DirectionActivity.class));
48 | }
49 |
50 | public void openOjek(View view) {
51 | startActivity(new Intent(this, OjekActivity.class));
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/app/src/main/java/com/khilman/www/learngoogleapi/OjekActivity.java:
--------------------------------------------------------------------------------
1 | package com.khilman.www.learngoogleapi;
2 |
3 | import android.Manifest;
4 | import android.annotation.SuppressLint;
5 | import android.content.Intent;
6 | import android.content.pm.PackageManager;
7 | import android.graphics.Color;
8 | import android.support.v4.app.ActivityCompat;
9 | import android.support.v7.app.AppCompatActivity;
10 | import android.os.Bundle;
11 | import android.util.Log;
12 | import android.view.View;
13 | import android.widget.Button;
14 | import android.widget.LinearLayout;
15 | import android.widget.TextView;
16 | import android.widget.Toast;
17 |
18 | import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
19 | import com.google.android.gms.common.GooglePlayServicesRepairableException;
20 | import com.google.android.gms.location.places.AutocompleteFilter;
21 | import com.google.android.gms.location.places.Place;
22 | import com.google.android.gms.location.places.ui.PlaceAutocomplete;
23 | import com.google.android.gms.maps.CameraUpdate;
24 | import com.google.android.gms.maps.CameraUpdateFactory;
25 | import com.google.android.gms.maps.GoogleMap;
26 | import com.google.android.gms.maps.OnMapReadyCallback;
27 | import com.google.android.gms.maps.SupportMapFragment;
28 | import com.google.android.gms.maps.model.LatLng;
29 | import com.google.android.gms.maps.model.LatLngBounds;
30 | import com.google.android.gms.maps.model.MarkerOptions;
31 | import com.google.android.gms.maps.model.PolylineOptions;
32 | import com.google.maps.android.PolyUtil;
33 | import com.khilman.www.learngoogleapi.network.ApiServices;
34 | import com.khilman.www.learngoogleapi.network.InitLibrary;
35 | import com.khilman.www.learngoogleapi.response.Distance;
36 | import com.khilman.www.learngoogleapi.response.Duration;
37 | import com.khilman.www.learngoogleapi.response.LegsItem;
38 | import com.khilman.www.learngoogleapi.response.ResponseRoute;
39 |
40 | import java.util.List;
41 |
42 | import retrofit2.Call;
43 | import retrofit2.Callback;
44 | import retrofit2.Response;
45 |
46 | public class OjekActivity extends AppCompatActivity implements OnMapReadyCallback {
47 | private GoogleMap mMap;
48 |
49 | private String API_KEY = "AIzaSyBe9P-itehQgH5BG7ox5vizpv5E1iGLMhg";
50 |
51 | public LatLng pickUpLatLng = null;
52 | public LatLng locationLatLng = null;
53 |
54 | private TextView tvStartAddress, tvEndAddress;
55 | private TextView tvPrice, tvDistance;
56 | private Button btnNext;
57 | private LinearLayout infoPanel;
58 | // Deklarasi variable
59 | private TextView tvPickUpFrom, tvDestLocation;
60 |
61 | public static final int PICK_UP = 0;
62 | public static final int DEST_LOC = 1;
63 | private static int REQUEST_CODE = 0;
64 |
65 | @Override
66 | protected void onCreate(Bundle savedInstanceState) {
67 | super.onCreate(savedInstanceState);
68 | setContentView(R.layout.activity_ojek);
69 | getSupportActionBar().setTitle("Ojek Hampir Online");
70 |
71 | // Inisialisasi Widget
72 | wigetInit();
73 | infoPanel.setVisibility(View.GONE);
74 | // Event OnClick
75 | tvPickUpFrom.setOnClickListener(new View.OnClickListener() {
76 | @Override
77 | public void onClick(View view) {
78 | // Jalankan Method untuk menampilkan Place Auto Complete
79 | // Bawa constant PICK_UP
80 | showPlaceAutoComplete(PICK_UP);
81 | }
82 | });
83 | // Event OnClick
84 | tvDestLocation.setOnClickListener(new View.OnClickListener() {
85 | @Override
86 | public void onClick(View view) {
87 | // Jalankan Method untuk menampilkan Place Auto Complete
88 | // Bawa constant DEST_LOC
89 | showPlaceAutoComplete(DEST_LOC);
90 | }
91 | });
92 |
93 |
94 | }
95 |
96 | // Method untuk Inisilisasi Widget agar lebih rapih
97 | private void wigetInit() {
98 | // Maps
99 | SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
100 | .findFragmentById(R.id.map);
101 | mapFragment.getMapAsync(this);
102 |
103 | infoPanel = findViewById(R.id.infoPanel);
104 | // Widget
105 | tvPickUpFrom = findViewById(R.id.tvPickUpFrom);
106 | tvDestLocation = findViewById(R.id.tvDestLocation);
107 |
108 | tvPrice = findViewById(R.id.tvPrice);
109 | tvDistance = findViewById(R.id.tvDistance);
110 | btnNext = findViewById(R.id.btnNext);
111 | }
112 |
113 | // Method menampilkan input Place Auto Complete
114 | private void showPlaceAutoComplete(int typeLocation) {
115 | // isi RESUT_CODE tergantung tipe lokasi yg dipilih.
116 | // titik jmput atau tujuan
117 | REQUEST_CODE = typeLocation;
118 |
119 | // Filter hanya tmpat yg ada di Indonesia
120 | AutocompleteFilter typeFilter = new AutocompleteFilter.Builder().setCountry("ID").build();
121 | try {
122 | // Intent untuk mengirim Implisit Intent
123 | Intent mIntent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
124 | .setFilter(typeFilter)
125 | .build(this);
126 | // jalankan intent impilist
127 | startActivityForResult(mIntent, REQUEST_CODE);
128 | } catch (GooglePlayServicesRepairableException e) {
129 | e.printStackTrace(); // cetak error
130 | } catch (GooglePlayServicesNotAvailableException e) {
131 | e.printStackTrace(); // cetak error
132 | // Display Toast
133 | Toast.makeText(this, "Layanan Play Services Tidak Tersedia", Toast.LENGTH_SHORT).show();
134 | }
135 |
136 | }
137 |
138 | @Override
139 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
140 | super.onActivityResult(requestCode, resultCode, data);
141 | //Toast.makeText(this, "Sini Gaes", Toast.LENGTH_SHORT).show();
142 | // Pastikan Resultnya OK
143 | if (resultCode == RESULT_OK) {
144 | //Toast.makeText(this, "Sini Gaes2", Toast.LENGTH_SHORT).show();
145 | // Tampung Data tempat ke variable
146 | Place placeData = PlaceAutocomplete.getPlace(this, data);
147 |
148 | if (placeData.isDataValid()) {
149 | // Show in Log Cat
150 | Log.d("autoCompletePlace Data", placeData.toString());
151 |
152 | // Dapatkan Detail
153 | String placeAddress = placeData.getAddress().toString();
154 | LatLng placeLatLng = placeData.getLatLng();
155 | String placeName = placeData.getName().toString();
156 |
157 | // Cek user milih titik jemput atau titik tujuan
158 | switch (REQUEST_CODE) {
159 | case PICK_UP:
160 | // Set ke widget lokasi asal
161 | tvPickUpFrom.setText(placeAddress);
162 | pickUpLatLng = placeData.getLatLng();
163 | break;
164 | case DEST_LOC:
165 | // Set ke widget lokasi tujuan
166 | tvDestLocation.setText(placeAddress);
167 | locationLatLng = placeData.getLatLng();
168 | break;
169 | }
170 | // Jalankan Action Route
171 | if (pickUpLatLng != null && locationLatLng != null) {
172 | actionRoute(placeLatLng, REQUEST_CODE);
173 | }
174 |
175 | } else {
176 | // Data tempat tidak valid
177 | Toast.makeText(this, "Invalid Place !", Toast.LENGTH_SHORT).show();
178 | }
179 | }
180 |
181 | }
182 |
183 | @SuppressLint("MissingPermission")
184 | @Override
185 | public void onMapReady(GoogleMap googleMap) {
186 | mMap = googleMap;
187 | mMap.setPadding(10, 180, 10, 10);
188 | mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
189 |
190 | mMap.setMyLocationEnabled(true);
191 | mMap.getUiSettings().setCompassEnabled(true);
192 | mMap.getUiSettings().setZoomGesturesEnabled(true);
193 | mMap.getUiSettings().setRotateGesturesEnabled(false);
194 | mMap.getUiSettings().setZoomControlsEnabled(true);
195 | }
196 |
197 | private void actionRoute(LatLng placeLatLng, int requestCode) {
198 | String lokasiAwal = pickUpLatLng.latitude + "," + pickUpLatLng.longitude;
199 | String lokasiAkhir = locationLatLng.latitude + "," + locationLatLng.longitude;
200 |
201 | // Clear dulu Map nya
202 | mMap.clear();
203 | // Panggil Retrofit
204 | ApiServices api = InitLibrary.getInstance();
205 | // Siapkan request
206 | Call routeRequest = api.request_route(lokasiAwal, lokasiAkhir, API_KEY);
207 | // kirim request
208 | routeRequest.enqueue(new Callback() {
209 | @Override
210 | public void onResponse(Call call, Response response) {
211 |
212 | if (response.isSuccessful()){
213 | // tampung response ke variable
214 | ResponseRoute dataDirection = response.body();
215 |
216 | LegsItem dataLegs = dataDirection.getRoutes().get(0).getLegs().get(0);
217 |
218 | // Dapatkan garis polyline
219 | String polylinePoint = dataDirection.getRoutes().get(0).getOverviewPolyline().getPoints();
220 | // Decode
221 | List decodePath = PolyUtil.decode(polylinePoint);
222 | // Gambar garis ke maps
223 | mMap.addPolyline(new PolylineOptions().addAll(decodePath)
224 | .width(8f).color(Color.argb(255, 56, 167, 252)))
225 | .setGeodesic(true);
226 |
227 | // Tambah Marker
228 | mMap.addMarker(new MarkerOptions().position(pickUpLatLng).title("Lokasi Awal"));
229 | mMap.addMarker(new MarkerOptions().position(locationLatLng).title("Lokasi Akhir"));
230 | // Dapatkan jarak dan waktu
231 | Distance dataDistance = dataLegs.getDistance();
232 | Duration dataDuration = dataLegs.getDuration();
233 |
234 | // Set Nilai Ke Widget
235 | double price_per_meter = 250;
236 | double priceTotal = dataDistance.getValue() * price_per_meter; // Jarak * harga permeter
237 |
238 | tvDistance.setText(dataDistance.getText());
239 | tvPrice.setText(String.valueOf(priceTotal));
240 | /** START
241 | * Logic untuk membuat layar berada ditengah2 dua koordinat
242 | */
243 |
244 | LatLngBounds.Builder latLongBuilder = new LatLngBounds.Builder();
245 | latLongBuilder.include(pickUpLatLng);
246 | latLongBuilder.include(locationLatLng);
247 |
248 | // Bounds Coordinata
249 | LatLngBounds bounds = latLongBuilder.build();
250 |
251 | int width = getResources().getDisplayMetrics().widthPixels;
252 | int height = getResources().getDisplayMetrics().heightPixels;
253 | int paddingMap = (int) (width * 0.2); //jarak dari
254 | CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, paddingMap);
255 | mMap.animateCamera(cu);
256 |
257 | /** END
258 | * Logic untuk membuat layar berada ditengah2 dua koordinat
259 | */
260 | // Tampilkan info panel
261 | infoPanel.setVisibility(View.VISIBLE);
262 |
263 | mMap.setPadding(10, 180, 10, 180);
264 |
265 | }
266 | }
267 |
268 | @Override
269 | public void onFailure(Call call, Throwable t) {
270 | t.printStackTrace();
271 | }
272 | });
273 | }
274 | }
275 |
--------------------------------------------------------------------------------
/app/src/main/java/com/khilman/www/learngoogleapi/PlaceAutoCompleteActivity.java:
--------------------------------------------------------------------------------
1 | package com.khilman.www.learngoogleapi;
2 |
3 | import android.content.Intent;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.os.Bundle;
6 | import android.util.Log;
7 | import android.view.View;
8 | import android.widget.TextView;
9 | import android.widget.Toast;
10 |
11 | import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
12 | import com.google.android.gms.common.GooglePlayServicesRepairableException;
13 | import com.google.android.gms.location.places.AutocompleteFilter;
14 | import com.google.android.gms.location.places.Place;
15 | import com.google.android.gms.location.places.ui.PlaceAutocomplete;
16 | import com.google.android.gms.maps.model.LatLng;
17 |
18 | public class PlaceAutoCompleteActivity extends AppCompatActivity {
19 |
20 |
21 | // Deklarasi variable
22 | private TextView tvPickUpFrom, tvDestLocation;
23 | private TextView tvPickUpAddr, tvPickUpLatLng, tvPickUpName;
24 | private TextView tvDestLocAddr, tvDestLocLatLng, tvDestLocName;
25 |
26 | public static final int PICK_UP = 0;
27 | public static final int DEST_LOC = 1;
28 | private static int REQUEST_CODE = 0;
29 | @Override
30 | protected void onCreate(Bundle savedInstanceState) {
31 | super.onCreate(savedInstanceState);
32 | setContentView(R.layout.activity_place_auto_complete);
33 |
34 | getSupportActionBar().setTitle("Place Auto Complete");
35 | // Inisialisasi Widget
36 | wigetInit();
37 |
38 | // Event OnClick
39 | tvPickUpFrom.setOnClickListener(new View.OnClickListener() {
40 | @Override
41 | public void onClick(View view) {
42 | // Jalankan Method untuk menampilkan Place Auto Complete
43 | // Bawa constant PICK_UP
44 | showPlaceAutoComplete(PICK_UP);
45 | }
46 | });
47 | // Event OnClick
48 | tvDestLocation.setOnClickListener(new View.OnClickListener() {
49 | @Override
50 | public void onClick(View view) {
51 | // Jalankan Method untuk menampilkan Place Auto Complete
52 | // Bawa constant DEST_LOC
53 | showPlaceAutoComplete(DEST_LOC);
54 | }
55 | });
56 | }
57 | // Method untuk Inisilisasi Widget agar lebih rapih
58 | private void wigetInit() {
59 | tvPickUpFrom = findViewById(R.id.tvPickUpFrom);
60 | tvDestLocation = findViewById(R.id.tvDestLocation);
61 | tvPickUpAddr = findViewById(R.id.tvPickUpAddr);
62 | tvPickUpLatLng = findViewById(R.id.tvPickUpLatLng);
63 | tvPickUpName = findViewById(R.id.tvPickUpName);
64 | tvDestLocAddr = findViewById(R.id.tvDestLocAddr);
65 | tvDestLocLatLng = findViewById(R.id.tvDestLocLatLng);
66 | tvDestLocName = findViewById(R.id.tvDestLocName);
67 | }
68 | // Method menampilkan input Place Auto Complete
69 | private void showPlaceAutoComplete(int typeLocation) {
70 | // isi RESUT_CODE tergantung tipe lokasi yg dipilih.
71 | // titik jmput atau tujuan
72 | REQUEST_CODE = typeLocation;
73 |
74 | // Filter hanya tmpat yg ada di Indonesia
75 | AutocompleteFilter typeFilter = new AutocompleteFilter.Builder().setCountry("ID").build();
76 | try {
77 | // Intent untuk mengirim Implisit Intent
78 | Intent mIntent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
79 | .setFilter(typeFilter)
80 | .build(this);
81 | // jalankan intent impilist
82 | startActivityForResult(mIntent, REQUEST_CODE);
83 | } catch (GooglePlayServicesRepairableException e) {
84 | e.printStackTrace(); // cetak error
85 | } catch (GooglePlayServicesNotAvailableException e) {
86 | e.printStackTrace(); // cetak error
87 | // Display Toast
88 | Toast.makeText(this, "Layanan Play Services Tidak Tersedia", Toast.LENGTH_SHORT).show();
89 | }
90 |
91 | }
92 |
93 | @Override
94 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
95 | super.onActivityResult(requestCode, resultCode, data);
96 | //Toast.makeText(this, "Sini Gaes", Toast.LENGTH_SHORT).show();
97 | // Pastikan Resultnya OK
98 | if (resultCode == RESULT_OK){
99 | //Toast.makeText(this, "Sini Gaes2", Toast.LENGTH_SHORT).show();
100 | // Tampung Data tempat ke variable
101 | Place placeData = PlaceAutocomplete.getPlace(this, data);
102 |
103 | if (placeData.isDataValid()){
104 | // Show in Log Cat
105 | Log.d("autoCompletePlace Data", placeData.toString());
106 |
107 | // Dapatkan Detail
108 | String placeAddress = placeData.getAddress().toString();
109 | LatLng placeLatLng = placeData.getLatLng();
110 | String placeName = placeData.getName().toString();
111 |
112 | // Cek user milih titik jemput atau titik tujuan
113 | switch (REQUEST_CODE){
114 | case PICK_UP:
115 | // Set ke widget lokasi asal
116 | tvPickUpFrom.setText(placeAddress);
117 | tvPickUpAddr.setText("Location Address : " + placeAddress);
118 | tvPickUpLatLng.setText("LatLang : " + placeLatLng.toString());
119 | tvPickUpName.setText("Place Name : " + placeName);
120 |
121 | break;
122 | case DEST_LOC:
123 | // Set ke widget lokasi tujuan
124 | tvDestLocation.setText(placeAddress);
125 | tvDestLocAddr.setText("Destination Address : " + placeAddress);
126 | tvDestLocLatLng.setText("LatLang : " + placeLatLng.toString());
127 | tvDestLocName.setText("Place Name : " + placeName);
128 |
129 | break;
130 | }
131 |
132 | } else {
133 | // Data tempat tidak valid
134 | Toast.makeText(this, "Invalid Place !", Toast.LENGTH_SHORT).show();
135 | }
136 | }
137 | }
138 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/khilman/www/learngoogleapi/network/ApiServices.java:
--------------------------------------------------------------------------------
1 | package com.khilman.www.learngoogleapi.network;
2 |
3 | import com.khilman.www.learngoogleapi.response.ResponseRoute;
4 |
5 | import retrofit2.Call;
6 | import retrofit2.http.GET;
7 | import retrofit2.http.Query;
8 |
9 | public interface ApiServices {
10 | //https://maps.googleapis.com/maps/api/directions/
11 | // json?origin=Cirebon,ID&destination=Jakarta,ID&api_key=YOUR_API_KEY
12 | @GET("json")
13 | Call request_route(
14 | @Query("origin") String origin,
15 | @Query("destination") String destination,
16 | @Query("api_key") String api_key
17 | );
18 | }
19 |
--------------------------------------------------------------------------------
/app/src/main/java/com/khilman/www/learngoogleapi/network/InitLibrary.java:
--------------------------------------------------------------------------------
1 | package com.khilman.www.learngoogleapi.network;
2 |
3 | import retrofit2.Retrofit;
4 | import retrofit2.converter.gson.GsonConverterFactory;
5 |
6 | public class InitLibrary {
7 | //https://maps.googleapis.com/maps/api/directions/json?origin=Cirebon,ID&destination=Jakarta,ID&api_key=YOUR_API_KEY
8 | public static String BASE_URL = "https://maps.googleapis.com/maps/api/directions/";
9 | public static Retrofit setInit(){
10 | return new Retrofit.Builder().baseUrl(BASE_URL)
11 | .addConverterFactory(GsonConverterFactory.create())
12 | .build();
13 | }
14 |
15 | public static ApiServices getInstance(){
16 | return setInit().create(ApiServices.class);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/app/src/main/java/com/khilman/www/learngoogleapi/response/Bounds.java:
--------------------------------------------------------------------------------
1 | package com.khilman.www.learngoogleapi.response;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | public class Bounds{
6 |
7 | @SerializedName("southwest")
8 | private Southwest southwest;
9 |
10 | @SerializedName("northeast")
11 | private Northeast northeast;
12 |
13 | public void setSouthwest(Southwest southwest){
14 | this.southwest = southwest;
15 | }
16 |
17 | public Southwest getSouthwest(){
18 | return southwest;
19 | }
20 |
21 | public void setNortheast(Northeast northeast){
22 | this.northeast = northeast;
23 | }
24 |
25 | public Northeast getNortheast(){
26 | return northeast;
27 | }
28 |
29 | @Override
30 | public String toString(){
31 | return
32 | "Bounds{" +
33 | "southwest = '" + southwest + '\'' +
34 | ",northeast = '" + northeast + '\'' +
35 | "}";
36 | }
37 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/khilman/www/learngoogleapi/response/Distance.java:
--------------------------------------------------------------------------------
1 | package com.khilman.www.learngoogleapi.response;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | public class Distance{
6 |
7 | @SerializedName("text")
8 | private String text;
9 |
10 | @SerializedName("value")
11 | private int value;
12 |
13 | public void setText(String text){
14 | this.text = text;
15 | }
16 |
17 | public String getText(){
18 | return text;
19 | }
20 |
21 | public void setValue(int value){
22 | this.value = value;
23 | }
24 |
25 | public int getValue(){
26 | return value;
27 | }
28 |
29 | @Override
30 | public String toString(){
31 | return
32 | "Distance{" +
33 | "text = '" + text + '\'' +
34 | ",value = '" + value + '\'' +
35 | "}";
36 | }
37 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/khilman/www/learngoogleapi/response/Duration.java:
--------------------------------------------------------------------------------
1 | package com.khilman.www.learngoogleapi.response;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | public class Duration{
6 |
7 | @SerializedName("text")
8 | private String text;
9 |
10 | @SerializedName("value")
11 | private int value;
12 |
13 | public void setText(String text){
14 | this.text = text;
15 | }
16 |
17 | public String getText(){
18 | return text;
19 | }
20 |
21 | public void setValue(int value){
22 | this.value = value;
23 | }
24 |
25 | public int getValue(){
26 | return value;
27 | }
28 |
29 | @Override
30 | public String toString(){
31 | return
32 | "Duration{" +
33 | "text = '" + text + '\'' +
34 | ",value = '" + value + '\'' +
35 | "}";
36 | }
37 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/khilman/www/learngoogleapi/response/EndLocation.java:
--------------------------------------------------------------------------------
1 | package com.khilman.www.learngoogleapi.response;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | public class EndLocation{
6 |
7 | @SerializedName("lng")
8 | private double lng;
9 |
10 | @SerializedName("lat")
11 | private double lat;
12 |
13 | public void setLng(double lng){
14 | this.lng = lng;
15 | }
16 |
17 | public double getLng(){
18 | return lng;
19 | }
20 |
21 | public void setLat(double lat){
22 | this.lat = lat;
23 | }
24 |
25 | public double getLat(){
26 | return lat;
27 | }
28 |
29 | @Override
30 | public String toString(){
31 | return
32 | "EndLocation{" +
33 | "lng = '" + lng + '\'' +
34 | ",lat = '" + lat + '\'' +
35 | "}";
36 | }
37 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/khilman/www/learngoogleapi/response/GeocodedWaypointsItem.java:
--------------------------------------------------------------------------------
1 | package com.khilman.www.learngoogleapi.response;
2 |
3 | import java.util.List;
4 | import com.google.gson.annotations.SerializedName;
5 |
6 | public class GeocodedWaypointsItem{
7 |
8 | @SerializedName("types")
9 | private List types;
10 |
11 | @SerializedName("geocoder_status")
12 | private String geocoderStatus;
13 |
14 | @SerializedName("place_id")
15 | private String placeId;
16 |
17 | public void setTypes(List types){
18 | this.types = types;
19 | }
20 |
21 | public List getTypes(){
22 | return types;
23 | }
24 |
25 | public void setGeocoderStatus(String geocoderStatus){
26 | this.geocoderStatus = geocoderStatus;
27 | }
28 |
29 | public String getGeocoderStatus(){
30 | return geocoderStatus;
31 | }
32 |
33 | public void setPlaceId(String placeId){
34 | this.placeId = placeId;
35 | }
36 |
37 | public String getPlaceId(){
38 | return placeId;
39 | }
40 |
41 | @Override
42 | public String toString(){
43 | return
44 | "GeocodedWaypointsItem{" +
45 | "types = '" + types + '\'' +
46 | ",geocoder_status = '" + geocoderStatus + '\'' +
47 | ",place_id = '" + placeId + '\'' +
48 | "}";
49 | }
50 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/khilman/www/learngoogleapi/response/LegsItem.java:
--------------------------------------------------------------------------------
1 | package com.khilman.www.learngoogleapi.response;
2 |
3 | import java.util.List;
4 | import com.google.gson.annotations.SerializedName;
5 |
6 | public class LegsItem{
7 |
8 | @SerializedName("duration")
9 | private Duration duration;
10 |
11 | @SerializedName("start_location")
12 | private StartLocation startLocation;
13 |
14 | @SerializedName("distance")
15 | private Distance distance;
16 |
17 | @SerializedName("start_address")
18 | private String startAddress;
19 |
20 | @SerializedName("end_location")
21 | private EndLocation endLocation;
22 |
23 | @SerializedName("end_address")
24 | private String endAddress;
25 |
26 | @SerializedName("via_waypoint")
27 | private List