Sei sulla pagina 1di 18

SOURCE CODE PROGRAM

//MainMenu Activity
package com.example.stmik_lab.gisperkara;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import include.DBConfig;
import include.GetPermission;
import include.JsonParser;
import include.PathUrl;

public class MainMenuActivity extends AppCompatActivity {

ImageView cAdd, cUser, cLog;


String userLogin, namaLogin;
LinearLayout lNotFound;
GetPermission getPermission;
TextView lLog;

ArrayList<HashMap<String, String>> listPerkara = new ArrayList<HashMap<String, String>> ();

private RecyclerView mRecyclerPus;


private RecyclerView.Adapter mAdapterPus;
private RecyclerView.LayoutManager mLayoutManagerPus;

private static final String TAG_PERKARA = "perkara";


public static final String TAG_CHECK = "check";
public static final String TAG_NO = "noperkara";
public static final String TAG_JENIS = "jenis";
public static final String TAG_TGL_DAFTAR = "tgldaftar";
public static final String TAG_TGL_SIDANG = "tglsidang";
public static final String TAG_WKT_SIDANG = "wktsidang";
public static final String TAG_JUM = "jumlahpihak";
public static final String TAG_STATUS = "statusperkara";
public static final String TAG_USER_LOGIN = "userlogin";

JsonParser jParser = new JsonParser();


DBConfig db;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
// toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
listPerkara = new ArrayList<HashMap<String, String>> ();
mRecyclerPus = (RecyclerView) findViewById(R.id.listRecycle);
mRecyclerPus.setHasFixedSize(true);
mLayoutManagerPus = new LinearLayoutManager(getApplicationContext());
mRecyclerPus.setLayoutManager(mLayoutManagerPus);
db = new DBConfig(this);
getPermission = new GetPermission(this);

getPermission.isAllowPermission();

//cAdd = (ImageView) findViewById(R.id.imgAdd);


//cUser = (ImageView) findViewById(R.id.imgListUser);
cLog = (ImageView) findViewById(R.id.imgLogout);
lLog = (TextView) findViewById(R.id.lLogout);
lNotFound = (LinearLayout) findViewById(R.id.lnotfound);

db.open();
Cursor c = db.selectData(db.tb_session, "id_, username", "status = '1'"); //cek user login
if(c.getCount() > 0){
userLogin = c.getString(c.getColumnIndexOrThrow("id_"));
namaLogin = c.getString(c.getColumnIndexOrThrow("username"));
lLog.setText("Logout ("+namaLogin+")");
new getPerkara().execute(userLogin);
}
db.close();

/*cAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), AddLokasi.class);
i.putExtra("PARAMS","NEW");
i.putExtra("IDS", "0"); //null
startActivity(i);
}
});

cUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), UserActivity.class);
startActivity(i);
}
});*/

cLog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

db.open();
if(db.isDelete(db.tb_session,"id_",userLogin)){
Intent i = new Intent(getApplicationContext(), MapsActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
db.close();

}
});
}

private class getPerkara extends AsyncTask<String, String, String> {


JSONObject json;
private ProgressDialog pDial;
JSONArray arrayPerkara = null;

@Override
protected void onPreExecute() {
pDial = new ProgressDialog(MainMenuActivity.this);
pDial.setMessage("Loading data perkara...");
pDial.setIndeterminate(false);
pDial.setCancelable(true);
pDial.show();
}

@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
HashMap<String, String> params = new HashMap<>();

params.put("idjurusita", arg0[0]);
try{
json = jParser.makeHttpRequest(PathUrl.URL_GET_PERKARA, "POST", params);

if(!json.equals(null)) {
arrayPerkara = json.getJSONArray(TAG_PERKARA);
}else{
Toast.makeText(getApplicationContext(),"Koneksi ke server bermasalah",Toast.LENGTH_LONG).show();
}
}catch (JSONException e){
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
pDial.dismiss();

try {
JSONObject jobx = arrayPerkara.getJSONObject(0);
if(!jobx.getString(TAG_CHECK).equals("false")) {
for(int i = 0; i < arrayPerkara.length(); i++) {
JSONObject job = arrayPerkara.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_CHECK, job.getString(TAG_CHECK).toString());
map.put(TAG_NO, job.getString(TAG_NO).toString());
map.put(TAG_JENIS, job.getString(TAG_JENIS).toString());
map.put(TAG_TGL_DAFTAR, job.getString(TAG_TGL_DAFTAR).toString());
map.put(TAG_TGL_SIDANG, job.getString(TAG_TGL_SIDANG).toString());
map.put(TAG_WKT_SIDANG, job.getString(TAG_WKT_SIDANG).toString());
map.put(TAG_JUM, job.getString(TAG_JUM).toString());
map.put(TAG_STATUS, job.getString(TAG_STATUS).toString());
map.put(TAG_USER_LOGIN, userLogin);

listPerkara.add(map);
}
}else{
lNotFound.setVisibility(View.VISIBLE);
}

} catch (Throwable e) {
Log.e(this.getClass().getSimpleName(), e.toString());
}

setListViewAdapter(listPerkara);

}
}

private void setListViewAdapter(ArrayList<HashMap<String, String>> data) {


// TODO Auto-generated method stub
mAdapterPus = new AdapterRecyclePerkara(MainMenuActivity.this,data);
mRecyclerPus.setAdapter(mAdapterPus);
}

}
//Maps Activity
package com.example.stmik_lab.gisperkara;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
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 org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import include.DBConfig;
import include.JsonParser;
import include.PathUrl;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;


DBConfig db;
private static String URL_LOGIN = PathUrl.URL_LOGIN;
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
ProgressBar pbLogin;

public void onAttachedToWindow() {


super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}

@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);

db = new DBConfig(this);
db.open();
Cursor c = db.selectData(db.tb_session, "id_", "status = '1'"); //cek user login
if(c.getCount() > 0){
Intent i = new Intent(this, MainMenuActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
db.close();

final EditText tUser = (EditText) findViewById(R.id.txtUsername);


final EditText tPass = (EditText) findViewById(R.id.txtKunciMasuk);
Button bLogin = (Button) findViewById(R.id.btnLogin);
pbLogin = (ProgressBar) findViewById(R.id.pbLogin);

bLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!TextUtils.isEmpty(tUser.getText().toString()) && !TextUtils.isEmpty(tPass.getText().toString())){
new getLogin().execute(tUser.getText().toString(), tPass.getText().toString());
}
}
});
}

private class getLogin extends AsyncTask<String, String, JSONObject> {

JSONObject json;
String usr, pwd;
JsonParser jParser = new JsonParser();

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pbLogin.setVisibility(View.VISIBLE);
}

@Override
protected JSONObject doInBackground(String... args) {
// TODO Auto-generated method stub
HashMap<String, String> param = new HashMap<>();
param.put("USR",args[0]);
param.put("PWD",args[1]);

usr = args[0];
pwd = args[1];

try{
json = jParser.makeHttpRequest(URL_LOGIN, "POST", param);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
return null;
}

@Override
protected void onPostExecute(JSONObject jsonObject) {
int success = 0;
String message = null;

pbLogin.setVisibility(View.GONE);

if (json != null) {
try {
success = json.getInt(TAG_SUCCESS);
message = json.getString(TAG_MESSAGE);

if(success > 0) {
String add = "'"+message.trim()+"','"+usr+"','"+pwd+"','1'";

db.open();
if(db.isSaveData(db.tb_session, add)){
Intent i = new Intent(getApplicationContext(), MainMenuActivity.class);
startActivity(i);
}else{
Toast.makeText(getApplicationContext(), "Gagal membuat session penyimpanan !",
Toast.LENGTH_SHORT).show();
}
db.close();

}else{
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}

} catch (JSONException e) {
e.printStackTrace();
}
}
}
}

/**
* 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;

LatLng koord = new LatLng(0.548922,123.005001);


mMap.addMarker(new MarkerOptions().position(koord).title(“Lokasi"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
//add pihak
package com.example.stmik_lab.gisperkara;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import include.DBConfig;
import include.DirectionsJSONParser;
import include.GPSTracker;
import include.GetPermission;
import include.JsonParser;
import include.PathUrl;

public class ActivityAddPihak extends AppCompatActivity implements


View.OnClickListener, LocationListener, GoogleMap.OnMarkerClickListener {

TextView tNama, tNik, tAlamat, tKelurahan, tTgl;

String filePathName = null, userLogin, IDS, encodedString;


Double recentLat, recentLng;
ImageView iFoto, iLoad, iBgFoto, iDate;
GetPermission getPermission;
GPSTracker gpsTracker;
DBConfig db;
Bitmap bitmap;

String [] pic;
HashMap<String, String> params = new HashMap<>();

File output = null, dir = null;


private static final int CONTENT_REQUEST = 1337;
private static final int RESULT_LOAD_IMG = 100;

private String LAT = "lat", LNG = "lng", ZOOM = "zoom", NAMA, ALAMAT, HP;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
SupportMapFragment mapFragment;
Marker marker;

double lat, lng;


LatLng lokasiAwal,tujuan;
PolylineOptions lineOptions;
Polyline polyline;

JsonParser jParser = new JsonParser();

ArrayList<HashMap<String, String>> listInfo = new ArrayList<HashMap<String, String>>();

private RecyclerView mRecyclerPus;


private RecyclerView.Adapter mAdapterPus;
private RecyclerView.LayoutManager mLayoutManagerPus;

public void onAttachedToWindow() {


super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_pihak);
getPermission = new GetPermission(this);
gpsTracker = new GPSTracker(ActivityAddPihak.this);
db = new DBConfig(this);

db.open();
Cursor cLogin = db.selectAllData(db.tb_session, "id_");
userLogin = cLogin.getString(cLogin.getColumnIndexOrThrow("id_"));
db.close();

tNama = (TextView) findViewById(R.id.tNamaRt);


tNik = (TextView) findViewById(R.id.tNikRt);
tAlamat = (TextView) findViewById(R.id.tAlamatRt);
tKelurahan = (TextView) findViewById(R.id.tTpsRt);
tTgl = (TextView) findViewById(R.id.tTgl);

iFoto = (ImageView) findViewById(R.id.imgFoto);


iLoad = (ImageView) findViewById(R.id.imgOpenFoto);
iBgFoto = (ImageView) findViewById(R.id.iv_header);
iDate = (ImageView) findViewById(R.id.iDate);

Intent i = getIntent();
if(i != null){

IDS = i.getStringExtra(ActivityDaftarPerkara.TAG_ID);
LAT = i.getStringExtra(ActivityDaftarPerkara.TAG_LAT);
LNG = i.getStringExtra(ActivityDaftarPerkara.TAG_LNG);
NAMA = i.getStringExtra(ActivityDaftarPerkara.TAG_NAMA);
ALAMAT = i.getStringExtra(ActivityDaftarPerkara.TAG_ALAMAT);
HP = i.getStringExtra(ActivityDaftarPerkara.TAG_HP);

tNama.setText(NAMA);
tNik.setText(i.getStringExtra(ActivityDaftarPerkara.TAG_ID)+" - Hp. "+HP);
tAlamat.setText(i.getStringExtra(ActivityDaftarPerkara.TAG_JENIS));
tKelurahan.setText(ALAMAT+". "+i.getStringExtra(ActivityDaftarPerkara.TAG_KEC)+".
"+i.getStringExtra(ActivityDaftarPerkara.TAG_KEL));

recentLat = gpsTracker.getLatitude();
recentLng = gpsTracker.getLongitude();

setUpMapIfNeeded(recentLat, recentLng, LAT, LNG, NAMA, ALAMAT, HP);


}

iFoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(getPermission.isAllowPermission()) {
openCamera();
}
}
});

iLoad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(getPermission.isAllowPermission()) {
getGallery();
}
}
});

iDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int mYear, mMonth, mDay;

final Calendar c = Calendar.getInstance();


mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);

DatePickerDialog datePickerDialog = new DatePickerDialog(getApplicationContext(), new


DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
tTgl.setText((monthOfYear + 1) + "/" + dayOfMonth + "/" + year);
}
}, mYear, mMonth, mDay);
}
});

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);


fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar snackbar = Snackbar.make(view, "Simpan data ?", Snackbar.LENGTH_LONG)
.setAction("YA", new View.OnClickListener() {
@Override
public void onClick(View v) {
try{

if(!TextUtils.isEmpty(tTgl.getText().toString())) {
params.put("TGL", tTgl.getText().toString());
uploadImage();
}else{
Toast.makeText(getApplicationContext(),"Inputkan tanggal pemanggilan pihak berperkara !",
Toast.LENGTH_SHORT).show();
}
}catch (Throwable e){
Toast.makeText(getApplicationContext(),"Foto belum dipilih !", Toast.LENGTH_SHORT).show();
}
}
});

snackbar.setActionTextColor(Color.YELLOW);
snackbar.show();
}
});
}

public void uploadImage(){


if (filePathName != null && pic[pic.length - 1] != null) {
new encodeImageToString().execute();
}
}

private class encodeImageToString extends AsyncTask<Void, Void, String> {


@Override
protected void onPreExecute() {}

@Override
protected String doInBackground(Void... params) {

BitmapFactory.Options options = null;


options = new BitmapFactory.Options();
options.inSampleSize = 3;
bitmap = BitmapFactory.decodeFile(filePathName,options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();

// Must compress the Image to reduce image size to make upload easy
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();

// Encode Image to String


encodedString = Base64.encodeToString(byte_arr, 0);

return null;
}

@Override
protected void onPostExecute(String result) {
params.put("ENC", encodedString);

Log.d("enc", encodedString);
new upImage().execute();
}
}

private class upImage extends AsyncTask<String, String, JSONObject> {


JsonParser jParser = new JsonParser();
private String URL_UP_IMAGE = PathUrl.URL_UPLOAD_IMAGE;

@Override
protected void onPreExecute() {
Log.d("param",""+params);
}

@Override
protected JSONObject doInBackground(String... args) {
// TODO Auto-generated method stub
try{
JSONObject json = jParser.makeHttpRequest(URL_UP_IMAGE, "POST", params);
if (json != null) {
Log.d("JSON result image", json.toString());
return json;
}
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
return null;
}

@Override
protected void onPostExecute(JSONObject json) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Intent i = new Intent(getApplicationContext(), MainMenuActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
});

}
}

private void openCamera() {


Intent i=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
output = new File(dir, IDS.trim()+".jpg");

i.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(ActivityAddPihak.this,
"com.example.stmik_lab.gisperkara.fileprovider", output));
startActivityForResult(i, CONTENT_REQUEST);
}
private void getGallery(){
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(Intent.createChooser(i, "Pilih Foto"), RESULT_LOAD_IMG);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub

if (requestCode == CONTENT_REQUEST) { //camera


if (resultCode == RESULT_OK) {
if (output.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(output.getAbsolutePath());
iBgFoto.setImageBitmap(myBitmap);
filePathName = output.getAbsolutePath();
}
}

}else if(requestCode == RESULT_LOAD_IMG){ //load pic

if(resultCode == ActivityAddPihak.RESULT_OK){
Uri selectedImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
iBgFoto.setImageBitmap(bitmap);
}catch (IOException e){
e.printStackTrace();
}

try {
filePathName = getFilePath(getApplicationContext(), data.getData());
pic = filePathName.split("/");
params.put("PIC",IDS+"~"+pic[pic.length-1]);
}catch (URISyntaxException e){
e.printStackTrace();
}
}
}
}

private void setUpMapIfNeeded(final Double recentLat, final Double recentLng, final String LAT, final String LNG,
final String nama, final String alamat, final String hp) {
if (mMap == null) {
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
if(getPermission.isAllowPermission()){
try {
mMap.setMyLocationEnabled(true);
}catch (Throwable e){
Log.e("AddtivityAddPihak", e.toString());
}
}

lokasiAwal= new LatLng(recentLat,recentLng);

mMap.addMarker(new MarkerOptions()
.position(lokasiAwal)
.title("Lokasi Saya")
.snippet(String.valueOf(String.valueOf(recentLat + "," + recentLng))));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(lokasiAwal, 14));

//mark lokasi pihak


marker = mMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(LAT),
Double.parseDouble(LNG)))
.title(nama)
.snippet(alamat + ". (HP) "+hp)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));

Log.d("Lokasi","DARI ("+lokasiAwal+") --> "+ LAT+","+LNG);

try {
if(lat != marker.getPosition().latitude && lng != marker.getPosition().longitude){
tujuan= new LatLng(Double.parseDouble(LAT), Double.parseDouble(LNG));
String url = getDirectionsUrl(lokasiAwal, tujuan); //0.57547776,123.07810254 //tujuan
0.5490078,123.0050009
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
}

} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(),"Error ! "+e.toString(), Toast.LENGTH_SHORT).show();
}

}
});
}

// fungsi mendapatkan rute


private String getDirectionsUrl(LatLng origin, LatLng dest) {
// Awal rute
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Tujuan rute
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Membuat parameters untuk dimasukkan web service rute map google
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// URL untuk eksekusi rute
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;

Log.d("url", url);
return url;
}

// Metode mendapatkan json data dari url

private String downloadUrl(String strUrl) throws IOException {


String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();

// menghubungkan ke url
urlConnection.connect();

// Membaca data dari url


iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();

String line = "";


while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();

} catch (Exception e) {
//Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}

// class untuk download data dari Google Directions URL


private class DownloadTask extends AsyncTask<String, Void, String> {

// Mendowload data dalam non-ui thread


@Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"Koneksi ke server bermasalah !", Toast.LENGTH_SHORT).show();
}
return data;
}

// di eksekusi di layar tampilan,setelah selesai ekseksui di


// doInBackground()
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Thread untuk parsing the JSON data
parserTask.execute(result);
}
}

/** Class untuk mengekstrak Google Directions dalam format JSON */


private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {

// Parsing data di dalam thread background


@Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {

JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;

try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Mulai parsing data
routes = parser.parse(jObject);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"Koneksi ke server bermasalah !", Toast.LENGTH_SHORT).show();
}
return routes;
}

// Mengeksekusi di tampilan setelah proses ektrak data selesai


@Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
lineOptions = null;

// Traversing through all the routes


for (int i = 0; i < result.size(); i++) {
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();

// Menginisialisasi i-th route


List<HashMap<String, String>> path = result.get(i);

// Fetching all the points in i-th route


for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);

double lat = Double.parseDouble(point.get("lat"));


double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);

points.add(position);
}

// Menambahkan semua points dalam rute ke LineOptions


lineOptions.addAll(points);
lineOptions.width(5);
lineOptions.color(Color.RED);

try {
polyline = mMap.addPolyline(lineOptions);
}catch (Throwable e){
Log.e("PolylineErr", e.toString());
}
}
}

@SuppressLint("NewApi")
public static String getFilePath(Context context, Uri uri) throws URISyntaxException {
String selection = null;
String[] selectionArgs = null;
// Uri is different in versions after KITKAT (Android 4.4), we need to
if (Build.VERSION.SDK_INT >= 19 && DocumentsContract.isDocumentUri(context.getApplicationContext(), uri)) {
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
return Environment.getExternalStorageDirectory() + "/" + split[1];
} else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
uri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
} else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("image".equals(type)) {
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
selection = "_id=?";
selectionArgs = new String[]{
split[1]
};
}
}
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = {
MediaStore.Images.Media.DATA
};
Cursor cursor = null;
try {
cursor = context.getContentResolver()
.query(uri, projection, selection, selectionArgs, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
}
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}

public static boolean isExternalStorageDocument(Uri uri) {


return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

public static boolean isDownloadsDocument(Uri uri) {


return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

public static boolean isMediaDocument(Uri uri) {


return "com.android.providers.media.documents".equals(uri.getAuthority());
}

@Override
public void onLocationChanged(Location location) {
lat = location.getLatitude();
lng = location.getLongitude();
}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

@Override
public void onProviderEnabled(String s) {

@Override
public void onProviderDisabled(String s) {

@Override
public void onClick(View view) {

@Override
public boolean onMarkerClick(Marker marker) {
if (marker.equals(marker)) {}
return true;
}

Potrebbero piacerti anche