반응형

Location과 Geocoder를 이용해 내 현재 위치와 다른 위치 사이의 거리를 구할 수 있다.

 

<AndroidManifest.xml>

1
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
 

 

<MainActivity.java>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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
public class MainActivity extends AppCompatActivity {
 
    final int MY_PERMISSION_REQUEST_GPS = 1001;
 
    Button button;
    Button button2;
    Button button3;
 
    EditText editText;
 
    TextView textView;
    TextView textView2;
    TextView textView3;
 
    Location myLocation;
    Location tarLocation;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        tarLocation = new Location("Target location");
        myLocation = new Location("My location");
 
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
 
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("info");
                builder.setMessage("This app won't work properly unless you grant GPS permission.");
                builder.setIcon(android.R.drawable.ic_dialog_info);
 
                builder.setNeutralButton("OK"new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions(MainActivity.thisnew String[] {Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_REQUEST_GPS);
                    }
                });
 
                AlertDialog dialog = builder.create();
                dialog.show();
            } else {
                ActivityCompat.requestPermissions(thisnew String[] {Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_REQUEST_GPS);
            }
        }
 
        textView = findViewById(R.id.textView);
        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocationService();
            }
        });
 
        final Geocoder geocoder = new Geocoder(this);
        editText = findViewById(R.id.editText);
        textView2 = findViewById(R.id.textView2);
        button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String search = editText.getText().toString();
                List<Address> addressList;
                try {
                    addressList = geocoder.getFromLocationName(search, 10);
                    String[] split = addressList.get(0).toString().split(",");
                    String address = split[0].substring(split[0].indexOf("\""+ 1split[0].length() - 2);
                    String latitude = split[10].substring(split[10].indexOf("="+ 1);  // 위도(수평선)
                    String longitude = split[12].substring(split[12].indexOf("="+ 1); // 경도(수직선)
 
                    String data = "Address: " + address + "\n" + "Latitude: " + latitude + "\n" + "Longitude: " + longitude;
                    textView2.setText(data);
                    tarLocation.setLatitude(Double.parseDouble(latitude));
                    tarLocation.setLongitude(Double.parseDouble(longitude));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
 
        textView3 = findViewById(R.id.textView3);
        button3 = findViewById(R.id.button3);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                float[] distance = new float[1];
                Location.distanceBetween(myLocation.getLatitude(), myLocation.getLongitude(), tarLocation.getLatitude(), tarLocation.getLongitude(), distance);
                textView3.setText("Distance: " + distance[0/ 1000.0f + "km");
                //textView3.setText("Distance: " + String.valueOf(myLocation.distanceTo(tarLocation) / 1000.0f) + "km");
            }
        });
    }
 
    public void startLocationService() {
        LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        try {
            Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (location != null) {
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                
                myLocation.setLatitude(latitude);
                myLocation.setLongitude(longitude);
                
                String message = "My last location\nLatitude: " + latitude + "\nLongitude: " + longitude;
                Log.d("App""Last location request");
                textView.setText(message);
            } else
            {
                Toast.makeText(this"location is null", Toast.LENGTH_SHORT).show();
            }
 
            GPSListener gpsListener = new GPSListener();
            long minTime = 3000;
            float minDistance = 0;
 
            manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, gpsListener);
            Log.d("App""Current location request");
        }catch (SecurityException e) {
            e.printStackTrace();
        }
    }
 
    class GPSListener implements LocationListener {
        public void onLocationChanged(Location location) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            String message = "My current location\nLatitude: " + latitude + "\nLongitude: " + longitude;
            textView.setText(message);
 
            myLocation.setLatitude(latitude);
            myLocation.setLongitude(longitude);
        }
 
        @Override
        public void onProviderEnabled(String provider) {
        }
 
        @Override
        public void onProviderDisabled(String provider) {
        }
 
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    }
 
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSION_REQUEST_GPS: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0== PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this,"Permission granted.",Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this,"Permission denied.",Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}
 

 

 

FIND MY CURRENT LOCATION 버튼을 클릭 한다. (내 위치는 분당 서현역)

 

주소를 입력하고 FIND ADDRESS LOCATION 버튼을 클릭 한다.

 

CALCULATE DISTANCE 버튼을 클릭 한다.

 

현재 위치(서현역)와 동탄역 사이의 (직선)거리가 표시 된다.

 

 

Google Map에서 계산한 거리와 거의 같다.

 

 

반응형
Posted by J-sean
: