TUTORIAL ANDROID MENENTUKAN JARAK TERDEKAT DENGAN FORMULA HAVERSINE


Nah langsung saja ini dia langkah – langkah dan codingnya
Buat tabel dengan nama lokasi dengan isi tabel sebagai berikut:
TUTORIAL ANDROID MENENTUKAN JARAK TERDEKAT DENGAN FORMULA HAVERSINE

Input kan data sebagai berikut:


Buat file php seperti berikut :

<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$dbhost = "mysql.idhostinger.com";
$dbuser = "u650837062_febri";
$dbpass = "satriafu150";
$dbname               = "u650837062_febri";

  mysql_connect($dbhost,$dbuser,$dbpass);
  mysql_select_db($dbname);

                $lat=$_GET['lat'];
                $lng=$_GET['lng'];
               
                $sql = "SELECT id, nama,latitude,longitude,
                (6371*ACOS(SIN(RADIANS(latitude))*SIN(RADIANS($lat))+COS(RADIANS(longitude - $lng))*COS(RADIANS(latitude))*COS(RADIANS($lat))))AS jarak
                FROM lokasi
                HAVING jarak < 6371
                ORDER BY jarak ASC limit 0,20";

                $hasil = mysql_query($sql);
                if($hasil>0)
                {
                                $response = array();
                                $response["lokasi"] = array();
                                while($data=mysql_fetch_array($hasil)){
                                               
                                                $h['id'] = $data['id'];
                                                $h['nama'] = $data['nama'];
                                                $h['latitude'] = $data['latitude'];
                                                $h['longitude'] = $data['longitude'];
                                                $h['jarak']=round($data['jarak'],1);
                                               
                                                array_push($response["lokasi"],$h);
                                }
                                $response["success"]="1";
                                echo json_encode($response);
                } else
                {
                                $response["success"]="0";
                                $response["message"]="Tidak ada data";
                                echo json_encode($response);
                }
?>


Nah  jika kita menggunakan hosting maka kita bisa mencoba untuk menjalankan lewat browser,  dibawah ini  adalah hasil  dari file php di atas :




Selanjutnya ini dia koding untuk android nya:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.febry.menentukanjarakdenganhaversine"
>

<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="15"
/>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme"
>
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>


 
JSONParser.java
 
 
package com.example.febry.menentukanjarakdenganhaversine;


import android.util.Log;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.client.utils.URLEncodedUtils;

import org.apache.http.impl.client.DefaultHttpClient;

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.io.UnsupportedEncodingException;

import java.util.List;



public class JSONParser {

static InputStream is = null;

static JSONObject jObj = null;

static String json = "";



public JSONParser() {



    }



public JSONObject getJSONFromUrl(String url) {

// http request

try {



            DefaultHttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(url);



            HttpResponse httpResponse = httpClient.execute(httpPost);

            HttpEntity httpEntity = httpResponse.getEntity();

is = httpEntity.getContent();



        } catch (UnsupportedEncodingException e) {

// TODO: handle exception

e.printStackTrace();

        } catch (ClientProtocolException e) {

// TODO: handle exception

e.printStackTrace();

        } catch (IOException e) {

// TODO: handle exception

e.printStackTrace();

        }



try {

            BufferedReader reader = new BufferedReader(new InputStreamReader(

is, "iso-8859-1"), 8);

            StringBuilder sb = new StringBuilder();

            String line = null;



while ((line = reader.readLine()) != null) {

                sb.append(line + "\n");

            }



is.close();

json = sb.toString();



        } catch (Exception e) {

// TODO: handle exception

Log.e("BUffer Error", "Error converting result" + e.toString());

        }



// try parse string to a json

try {

jObj = new JSONObject(json);

        } catch (JSONException e) {

// TODO: handle exception

Log.e("Json parser", "error parsing data" + e.toString());

        }



return jObj;

    }



public JSONObject makeHttpRequest(String url, String method,

                                      List<NameValuePair> params){



// membuat request HTTP

try {



// cek untuk method request

if (method.equalsIgnoreCase("post")) {

// jika request method adalah POST

                // defaultHttpClient

DefaultHttpClient httpClient = new DefaultHttpClient();

                HttpPost httpPost = new HttpPost(url);

                httpPost.setEntity(new UrlEncodedFormEntity(params));



                HttpResponse httpResponse = httpClient.execute(httpPost);

                HttpEntity httpEntity = httpResponse.getEntity();

is = httpEntity.getContent();



            } else if (method.equalsIgnoreCase("get")) {

// jika request method adalah GET

DefaultHttpClient httpClient = new DefaultHttpClient();

                String paramString = URLEncodedUtils.format(params, "utf-8");

                url += "?" + paramString;

                HttpGet httpGet = new HttpGet(url);



                HttpResponse httpResponse = httpClient.execute(httpGet);

                HttpEntity httpEntity = httpResponse.getEntity();

is = httpEntity.getContent();

            }



        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();

        } catch (ClientProtocolException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }



try {

            BufferedReader reader = new BufferedReader(new InputStreamReader(

is, "iso-8859-1"), 8);

            StringBuilder sb = new StringBuilder();

            String line = null;

while ((line = reader.readLine()) != null) {

                sb.append(line + "\n");

            }

is.close();

json = sb.toString();

        } catch (Exception e) {

            Log.e("Buffer Error", "Error converting result " + e.toString());

        }



try {

// try parse the string into JSON object and REMOVE invisible character (<br>,<html>)

jObj = new JSONObject(json);//.substring(json.indexOf("{"), json.lastIndexOf("}") + 1)

} catch (JSONException e) {

            Log.i("JSON Parser",json.toString());

            Log.e("JSON Parser", "Error parsing data " + e.toString());

        }



// return JSON String

return jObj;



    }



}
 
GpsService.java
 
package com.example.febry.menentukanjarakdenganhaversine;



import android.app.AlertDialog;

import android.app.Service;

import android.content.Context;

import android.content.DialogInterface;

import android.content.Intent;

import android.location.Location;

import android.location.LocationListener;

import android.location.LocationManager;

import android.os.Bundle;

import android.os.IBinder;

import android.provider.Settings;





public class GpsService extends Service implements LocationListener {
private final Context _context;

boolean GPSEnable = false;

boolean GetLocation = false;

    Location location;

double lat;

double lng;

private static final long MIN_JARAK_GPS_UPDATE = 5;

private static final long MIN_WAKTU_GPS_UPDATE = 1000 * 60 * 1;

protected LocationManager LocationBasedService;





public GpsService(Context context) {

_context = context;

        getLocation();

    }



private Location getLocation() {

try {

LocationBasedService = (LocationManager) _context.getSystemService(LOCATION_SERVICE);



GPSEnable = LocationBasedService.isProviderEnabled(LocationManager.GPS_PROVIDER);

if (!GPSEnable)

            {

// tidak ada koneksi ke GPS dan Jaringan

}

else {

GetLocation = true;

if (GPSEnable) {

if (location == null){

LocationBasedService.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_WAKTU_GPS_UPDATE,MIN_JARAK_GPS_UPDATE, this);

if (LocationBasedService != null) {

location = LocationBasedService.getLastKnownLocation(LocationManager.GPS_PROVIDER);

if (location != null) {

lat = location.getLatitude();

lng = location.getLongitude();

                            }}}}

            }

        }

catch (Exception e) {

            e.printStackTrace();

        }

return location;

    }



@Override

public void onLocationChanged(Location location)

    {

// TODO Auto-generated method stub

}



@Override

public void onProviderDisabled(String provider) {

// TODO Auto-generated method stub

}



@Override

public void onProviderEnabled(String provider) {

// TODO Auto-generated method stub

}



@Override

public void onStatusChanged(String provider, int status, Bundle extras)

    {

// TODO Auto-generated method stub

}



@Override

public IBinder onBind(Intent intent)

    {

// TODO Auto-generated method stub

return null;

    }

public double getLatitude()

    {

if (location != null)

lat = location.getLatitude();

return lat;

    }

public void setLatitude(double lat)

    {

this.lat = lat;

    }

public double getLongitude()

    {

if (location != null)

lng = location.getLongitude();

return lng;

    }

public void setLongitude(double lng)

    {

this.lng = lng;

    }

public boolean GetLocation()

    {

return this.GetLocation;

    }

public void showSettingAlert()

    {

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(_context);

        alertDialog.setTitle("GPS Setting");

        alertDialog.setMessage("GPS tidak aktif. Mau masuk ke setting Menu ?");

        alertDialog.setPositiveButton("Setting", new DialogInterface.OnClickListener()

        {

@Override

public void onClick(DialogInterface dialog, int which)

            {

                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);

_context.startActivity(intent);

            }

        });

        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener()

        {

@Override

public void onClick(DialogInterface dialog, int which)

            {

                dialog.cancel();

            }

        });

        alertDialog.show();

    }



public void stopUsingGPS()

    {

if (LocationBasedService != null)

LocationBasedService.removeUpdates(GpsService.this);

    }

}
 
 

MainActivity.java


package com.example.febry.menentukanjarakdenganhaversine;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    ProgressDialog pDialog;
    String status = "1";
    JSONArray college = null;
    ListView lve;
    GpsService  gps;
private static final String TAG_IDMEM = "id";
private static final String TAG_NAMA = "nama";
private static final String TAG_JARAK = "jarak";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

lve = (ListView) findViewById(R.id.list_daftar);

gps = new GpsService(MainActivity.this);
if (gps.GetLocation())
        {
double lat = gps.getLatitude();
double lng = gps.getLongitude();
new AmbilData().execute(String.valueOf(lat), String.valueOf(lng));
        }
else
{
gps.showSettingAlert();
        }

lve.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
// String idmem = ((TextView) view.findViewById(R.id.idmem)).getText().toString();
               // Intent x = new Intent(getApplicationContext(), MainActivity.class);
               // x.putExtra(TAG_IDMEM, idmem);
              //  startActivity(x);
}

        });
    }

public class AmbilData extends AsyncTask<String, String, String> {

        ArrayList<HashMap<String,String>>dataList = new ArrayList<HashMap<String, String>>();
@Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Mengambil data. Silahkan tunggu...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
        }

@Override
protected String doInBackground(String... args)
        {
            String lat = args[0];
            String lng = args[1];
            ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
            param.add(new BasicNameValuePair("lat", lat));
            param.add(new BasicNameValuePair("lng",lng));
            String url;
            url = "http://febri607.esy.es/lokasi.php";

            JSONParser jParser = new JSONParser();
            JSONObject json = jParser.makeHttpRequest(url,"GET",param);
try{
college = json.getJSONArray("lokasi");

                String success = json.getString("success");

if(success.equals("1")){
for (int i = 0; i <college.length(); i++){
                        JSONObject c = college.getJSONObject(i);
                        HashMap<String, String> map = new HashMap<String, String>();

                        String id = c.getString(TAG_IDMEM);
                        String nama = c.getString(TAG_NAMA);
                        String jarak = c.getString(TAG_JARAK);

                        map.put(TAG_IDMEM, id);
                        map.put(TAG_NAMA, nama);
                        map.put(TAG_JARAK, jarak);

dataList.add(map);
                    }
                }else{
pDialog.dismiss();
status ="0";
                }
            }catch(JSONException e){
pDialog.dismiss();
            }
return null;
        }

@Override
protected void onPostExecute(String result){
super.onPostExecute(result);
pDialog.dismiss();
if(status.equals("0")){
                Toast.makeText(getApplicationContext(),"data tidak ada", Toast.LENGTH_SHORT).show();
            }
            ListAdapter adapter = new SimpleAdapter(getApplicationContext(),
dataList, R.layout.list_item, new String[] {TAG_IDMEM,TAG_NAMA,TAG_JARAK},
new int[] {R.id.idmem,R.id.nama,R.id.jarak});

lve.setAdapter(adapter);
        }
    }

}


activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DAFTAR LOKASI"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="25dp"
android:paddingTop="10dp"
android:textColor="#0a3df9"
android:textStyle="italic"
android:singleLine="true"
android:scrollIndicators="top"
android:gravity="center|start"
android:foregroundGravity="center"
android:layout_gravity="center"
android:layout_marginTop="20dp"
/>

<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/list_daftar"
android:layout_below="@+id/textView"
android:paddingTop="10dp"
/>

</RelativeLayout>


list_item.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:orientation="vertical"
android:background="#ccc8c8"
>

<!-- id anggota (idmem) - akan di sembunyikan - digunakan untuk mengirim variabel id ke activity lain -->

<!-- Name Label -->

<!-- alamat anggota (alamat) - akan di sembunyikan - digunakan untuk mengirim variabel alamat ke activity lain -->

<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:id="@+id/idmem"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
/>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Nama"
android:id="@+id/nama"
android:textColor="#000000"
android:textSize="20dp"
android:layout_marginLeft="7dp"
android:layout_marginStart="7dp"
android:layout_above="@+id/idmem"
android:layout_toRightOf="@+id/imageView"
/>

<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="@+id/imageView"
android:background="#06f80e"
android:layout_centerVertical="true"
android:layout_toRightOf="@+id/idmem"
android:layout_toEndOf="@+id/idmem"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Jarak  :  "
android:id="@+id/jarak1"
android:textColor="#000000"
android:textSize="12dp"
android:layout_alignTop="@+id/jarak"
android:layout_alignLeft="@+id/nama"
android:layout_alignStart="@+id/nama"
/>

<TextView
android:layout_width="40dp"
android:layout_height="14dp"
android:id="@+id/jarak"
android:textColor="#000000"
android:textSize="12dp"
android:layout_alignBottom="@+id/imageView"
android:layout_toRightOf="@+id/jarak1"
android:layout_toEndOf="@+id/jarak1"
/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="km"
android:id="@+id/textView2"
android:textSize="12dp"
android:textColor="#000000"
android:layout_alignTop="@+id/jarak"
android:layout_toRightOf="@+id/jarak"
android:layout_toEndOf="@+id/jarak"
/>

</RelativeLayout>
Jangan lupa untuk di bagian build.gradle(Module: app) kita tambahkan



Tambah kan sitak di bawah ini padabagian yang saya buri tanda palik besar
compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
compile 'com.google.android.gms:play-services:8.4.0'
Semoga bermanfaat.......jangan lupa beri like dan komen.

2 Responses to "TUTORIAL ANDROID MENENTUKAN JARAK TERDEKAT DENGAN FORMULA HAVERSINE"