Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, DirectionFinderListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
- {
- private Geocoder geocoder;
- private GoogleMap mMap;
- private FloatingActionButton btnFindPath;
- private TextView btnLanjutkan;
- private TextView btnLihatLokasi;
- private EditText etOrigin;
- private EditText etDestination;
- private List<Marker> originMarkers = new ArrayList<>();
- private List<Marker> destinationMarkers = new ArrayList<>();
- private List<Polyline> polylinePaths = new ArrayList<>();
- private List<Address> addresses;
- private ProgressDialog progressDialog;
- protected LocationManager locationManager;
- private Location mLastLocation;
- private Context context;
- protected String latitude, longitude;
- private FusedLocationProviderClient mFusedLocationClient;
- protected double lng, lat;
- private GoogleApiClient googleApiClient;
- private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
- private int pid;
- TextView ongkir;
- private int market = 0;
- SupportMapFragment mapFragment;
- private boolean isMarket;
- private Marker dest;
- private boolean fromsearch = false;
- private ImageView BBack;
- Dialog dialog;
- private void AskMarket()
- {
- dialog = new Dialog(MapsActivity.this);
- dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
- dialog.setCancelable(false);
- dialog.setContentView(R.layout.dialog_three_button);
- TextView BOne = dialog.findViewById(R.id.BOne);
- TextView BTwo = dialog.findViewById(R.id.BTwo);
- TextView BThree = dialog.findViewById(R.id.BThree);
- TextView LDesc = dialog.findViewById(R.id.LDesc);
- TextView title = dialog.findViewById(R.id.title);
- title.setText("Pilih Market");
- LDesc.setText("Untuk melanjutkan, silakan pilih Market yang dikehendaki");
- BOne.setText("Pasar Manis");
- BTwo.setText("Pasar Wage");
- BThree.setText("Pasar Cermei");
- BOne.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- market = 0;
- InitGMaps();
- }
- });
- BTwo.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- market = 1;
- InitGMaps();
- }
- });
- BThree.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- market = 2;
- InitGMaps();
- }
- });
- dialog.show();
- }
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_maps);
- isMarket = getIntent().getBooleanExtra("isMarket", true);
- // Obtain the SupportMapFragment and get notified when the map is ready to be used.
- if (isMarket)
- AskMarket();
- else
- {
- mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
- mapFragment.getMapAsync(this);
- }
- ongkir = (TextView) findViewById(R.id.tvPrice);
- btnLihatLokasi = (TextView) findViewById(R.id.btnLihatLokasi);
- btnFindPath = (FloatingActionButton) findViewById(R.id.btnFindPath);
- btnLanjutkan = (TextView) findViewById(R.id.btnLanjutkan);
- etOrigin = (EditText) findViewById(R.id.etOrigin);
- etDestination = (EditText) findViewById(R.id.etDestination);
- BBack = findViewById(R.id.BBack);
- BBack.setOnClickListener(new View.OnClickListener()
- {
- @Override
- public void onClick(View v)
- {
- onBackPressed();
- }
- });
- if (checkPlayServices()) {
- // Building the GoogleApi client
- buildGoogleApiClient();
- }
- btnLihatLokasi.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- btnLihatLokasi.setEnabled(false);
- requestmyloc();
- callatruntime();
- }
- });
- btnFindPath.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- fromsearch = true;
- sendRequest(etDestination.getText().toString());
- }
- });
- btnLanjutkan.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if (etDestination.getText().toString().isEmpty()) {
- Toast.makeText(getApplicationContext(), "Isi Alamat Terlbih Dahulu", Toast.LENGTH_SHORT).show();
- } else if (ongkir.getText().toString().equals("0")) {
- Toast.makeText(getApplicationContext(), "Klik Tombol Pencarian untuk Mengetahui ongkir", Toast.LENGTH_SHORT).show();
- } else {
- String tujuan = etDestination.getText().toString();
- int ongkos = Integer.valueOf(ongkir.getText().toString());
- Intent intent = new Intent(getApplicationContext(), FinishMarketActivity.class);
- intent.putExtra("isMarket", isMarket);
- intent.putExtra("tujuan", tujuan);
- intent.putExtra("ongkir", ongkos);
- intent.putExtra("market", market);
- startActivity(intent);
- }
- }
- });
- }
- public void callatruntime() {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
- checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
- requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, pid);
- } else {
- Toast.makeText(this, "Location Permission Granted", Toast.LENGTH_SHORT).show();
- }
- }
- @Override
- public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
- if (requestCode == pid) {
- if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- callatruntime();
- } else {
- Toast.makeText(getApplicationContext(), "Not Granted", Toast.LENGTH_LONG).show();
- }
- }
- }
- private void requestmyloc() {
- btnLihatLokasi.setEnabled(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;
- }
- mLastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
- if (mLastLocation != null) {
- double latitude = mLastLocation.getLatitude();
- double longitude = mLastLocation.getLongitude();
- String origin = etOrigin.getText().toString() + " Purwokerto";
- Log.d("Longitude", String.valueOf(longitude));
- etDestination.setText(GetAddress(latitude, longitude));
- sendRequest(String.valueOf(latitude + "," + longitude));
- } else {
- Log.d("error", "message");
- }
- }
- private String GetAddress(double lat, double lng)
- {
- Geocoder geocoder = new Geocoder(this);
- try
- {
- List<Address> addresses = geocoder.getFromLocation(lat, lng,1);
- String address = addresses.get(0).getAddressLine(0);
- String city = addresses.get(0).getAddressLine(1);
- //String country = addresses.get(0).getAddressLine(2);
- if (address != null){
- return address;
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- return "Tidak Ditemukan";
- }
- private void sendRequest(String destination) {
- String origin = etOrigin.getText().toString() + " Purwokerto";
- if (origin.isEmpty()) {
- Toast.makeText(this, "Please enter origin address!", Toast.LENGTH_SHORT).show();
- return;
- }
- if (destination.isEmpty()) {
- Toast.makeText(this, "Please enter destination address!", Toast.LENGTH_SHORT).show();
- return;
- }
- Log.d("##############", "sendRequest: " + destination);
- try {
- new DirectionFinder(this, origin, destination).execute();
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- }
- private void InitGMaps()
- {
- dialog.cancel();
- mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
- mapFragment.getMapAsync(this);
- }
- @Override
- public void onMapReady(GoogleMap googleMap) {
- mMap = googleMap;
- mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener()
- {
- @Override
- public void onMapClick(LatLng latLng)
- {
- fromsearch = false;
- dest.setVisible(true);
- dest.setPosition(latLng);
- sendRequest(String.valueOf(latLng.latitude + "," + latLng.longitude));
- etDestination.setText(GetAddress(latLng.latitude, latLng.longitude));
- }
- });
- LatLng hcmus = new LatLng(-7.417905, 109.227261);
- dest = mMap.addMarker(new MarkerOptions().title("Tujuan").icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_blue2)).position(hcmus));
- dest.setVisible(false);
- String marketname = "Pasar Manis";
- if (isMarket)
- {
- switch (market)
- {
- case 0:
- {
- hcmus = new LatLng(-7.417905, 109.227261);
- marketname = "Pasar Manis";
- break;
- }
- case 1:
- {
- hcmus = new LatLng(-7.426289, 109.250309);
- marketname = "Pasar Wage";
- break;
- }
- case 2:
- {
- hcmus = new LatLng(-7.397284, 109.232166);
- marketname = "Pasar Cerme";
- break;
- }
- }
- }
- else
- {
- marketname = "Kopkun Swalayan";
- hcmus = new LatLng(-7.407896999999999, 109.24528499999997);
- }
- etOrigin.setText(marketname);
- mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(hcmus, 18));
- originMarkers.add(mMap.addMarker(new MarkerOptions()
- .title(marketname)
- .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_location2))
- .position(hcmus))
- );
- 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);
- }
- @Override
- public void onDirectionFinderStart() {
- progressDialog = ProgressDialog.show(this, "Please wait.",
- "Finding direction..!", true);
- if (originMarkers != null) {
- for (Marker marker : originMarkers) {
- marker.remove();
- }
- }
- if (destinationMarkers != null) {
- for (Marker marker : destinationMarkers) {
- marker.remove();
- }
- }
- if (polylinePaths != null) {
- for (Polyline polyline:polylinePaths ) {
- polyline.remove();
- }
- }
- }
- @OnClick(R.id.BBack)
- public void back(){
- onBackPressed();
- }
- @Override
- public void onDirectionFinderSuccess(List<Route> routes) {
- progressDialog.dismiss();
- polylinePaths = new ArrayList<>();
- originMarkers = new ArrayList<>();
- destinationMarkers = new ArrayList<>();
- for (Route route : routes) {
- if (fromsearch)
- {
- mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.endLocation, 18));
- destinationMarkers.add(mMap.addMarker(new MarkerOptions()
- .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_blue2))
- .title(route.endAddress)
- .position(route.endLocation)));
- }
- TextView jarak = (TextView) findViewById(R.id.tvDistance);
- TextView waktu = (TextView) findViewById(R.id.tvDuration);
- jarak.setText(String.valueOf(route.distance.value));
- waktu.setText(String.valueOf(route.duration.value));
- btnLihatLokasi.setEnabled(false);
- int changeJarak = Integer.parseInt(jarak.getText().toString());
- int changeWaktu = Integer.parseInt(waktu.getText().toString());
- int awal = 7700;
- int jarakawal = changeJarak/1000;
- if (jarakawal < 5){
- ongkir.setText(String.valueOf(awal));
- jarak.setText(String.valueOf(changeJarak/1000));
- waktu.setText(String.valueOf(changeWaktu/60));
- } else {
- ongkir.setText(String.valueOf((jarakawal - 5) * 1600 + awal));
- jarak.setText(String.valueOf(changeJarak/1000));
- waktu.setText(String.valueOf(changeWaktu/60));
- }
- //((TextView) findViewById(R.id.tvPrice)).setText(route.price.text);
- originMarkers.add(mMap.addMarker(new MarkerOptions()
- .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_location2))
- .title(route.startAddress)
- .position(route.startLocation)));
- PolylineOptions polylineOptions = new PolylineOptions().
- geodesic(true).
- color(R.color.colorPrimary).
- width(10);
- for (int i = 0; i < route.points.size(); i++)
- polylineOptions.add(route.points.get(i));
- polylinePaths.add(mMap.addPolyline(polylineOptions));
- }
- }
- /**
- * Creating google api client object
- * */
- protected synchronized void buildGoogleApiClient() {
- googleApiClient = new GoogleApiClient.Builder(this)
- .addConnectionCallbacks(this)
- .addOnConnectionFailedListener(this)
- .addApi(LocationServices.API).build();
- }
- /**
- * Method to verify google play services on the device
- * */
- private boolean checkPlayServices() {
- int resultCode = GooglePlayServicesUtil
- .isGooglePlayServicesAvailable(this);
- if (resultCode != ConnectionResult.SUCCESS) {
- if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
- GooglePlayServicesUtil.getErrorDialog(resultCode, this,
- PLAY_SERVICES_RESOLUTION_REQUEST).show();
- } else {
- Toast.makeText(getApplicationContext(),
- "This device is not supported.", Toast.LENGTH_LONG)
- .show();
- finish();
- }
- return false;
- }
- return true;
- }
- @Override
- protected void onStart() {
- super.onStart();
- if (googleApiClient != null) {
- googleApiClient.connect();
- }
- }
- @Override
- protected void onResume() {
- super.onResume();
- checkPlayServices();
- }
- @Override
- public void onConnected(@Nullable Bundle bundle) {
- /*requestmyloc();*/
- }
- @Override
- public void onConnectionSuspended(int i) {
- googleApiClient.connect();
- }
- @Override
- public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement