Map.java
16 KB
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
package com.example.user.firebaseauthdemo;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApi;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceLikelihood;
import com.google.android.gms.location.places.PlaceLikelihoodBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
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;
/**
* Created by HYB on 2017. 10. 11..
*/
public class Map extends Fragment
implements OnMapReadyCallback ,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
{
private static final LatLng DEFAULT_LOCATION = new LatLng(37.56, 126.97);
private static final String TAG = "googlemap_example";
private static final int GPS_ENABLE_REQUEST_CODE = 2001;
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 2002;
private static final int UPDATE_INTERVAL_MS = 15000;
private static final int FASTEST_UPDATE_INTERVAL_MS = 15000;
private GoogleMap googleMap = null;
private MapView mapView = null;
private GoogleApiClient googleApiClient = null;
private Marker currentMarker = null;
private final static int MAXENTRIES = 5;
private String[] LikelyPlaceNames = null;
private String[] LikelyAddresses = null;
private String[] LikelyAttributions = null;
private LatLng[] LikelyLatLngs = null;
public Map()
{
}
public void setCurrentLocation(Location location, String markerTitle, String markerSnippet) {
if ( currentMarker != null ) currentMarker.remove();
if ( location != null) {
//현재위치의 위도 경도 가져옴
LatLng currentLocation = new LatLng( location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(currentLocation);
markerOptions.title(markerTitle);
markerOptions.snippet(markerSnippet);
markerOptions.draggable(true);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
currentMarker = this.googleMap.addMarker(markerOptions);
this.googleMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
return;
}
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(DEFAULT_LOCATION);
markerOptions.title(markerTitle);
markerOptions.snippet(markerSnippet);
markerOptions.draggable(true);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
currentMarker = this.googleMap.addMarker(markerOptions);
this.googleMap.moveCamera(CameraUpdateFactory.newLatLng(DEFAULT_LOCATION));
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
View layout = inflater.inflate(R.layout.map, container, false);
mapView = (MapView)layout.findViewById(R.id.mapView);
mapView.getMapAsync(this);
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getActivity().getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
Location location = new Location("");
location.setLatitude(place.getLatLng().latitude);
location.setLongitude(place.getLatLng().longitude);
setCurrentLocation(location, place.getName().toString(), place.getAddress().toString());
}
@Override
public void onError(Status status) {
Log.i(TAG, "An error occurred: " + status);
}
});
return layout;
}
@Override
public void onStart()
{
super.onStart();
mapView.onStart();
}
@Override
public void onStop()
{
super.onStop();
mapView.onStop();
if ( googleApiClient != null && googleApiClient.isConnected())
googleApiClient.disconnect();
}
@Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public void onResume()
{
super.onResume();
mapView.onResume();
if ( googleApiClient != null)
googleApiClient.connect();
}
@Override
public void onPause()
{
super.onPause();
mapView.onPause();
if ( googleApiClient != null && googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, (com.google.android.gms.location.LocationListener) this);
googleApiClient.disconnect();
}
}
@Override
public void onLowMemory()
{
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onDestroy()
{
super.onDestroy();
mapView.onLowMemory();
if ( googleApiClient != null ) {
googleApiClient.unregisterConnectionCallbacks(this);
googleApiClient.unregisterConnectionFailedListener(this);
if ( googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, (com.google.android.gms.location.LocationListener) this);
googleApiClient.disconnect();
}
}
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
//액티비티가 처음 생성될 때 실행되는 함수
MapsInitializer.initialize(getActivity().getApplicationContext());
if (mapView != null)
{
mapView.onCreate(savedInstanceState);
}
}
@Override
public void onMapReady(GoogleMap googleMap)
{
//
// LatLng SEOUL = new LatLng(37.56, 126.97);
// MarkerOptions markerOptions = new MarkerOptions();
// markerOptions.position(SEOUL);
// markerOptions.title("서울");
// markerOptions.snippet("수도");
// googleMap.addMarker(markerOptions);
// googleMap.moveCamera(CameraUpdateFactory.newLatLng(SEOUL));
// googleMap.animateCamera(CameraUpdateFactory.zoomTo(13));
// OnMapReadyCallback implements 해야 mapView.getMapAsync(this); 사용가능. this 가 OnMapReadyCallback
this.googleMap = googleMap;
//런타임 퍼미션 요청 대화상자나 GPS 활성 요청 대화상자 보이기전에 지도의 초기위치를 서울로 이동
setCurrentLocation(null, "위치정보 가져올 수 없음", "위치 퍼미션과 GPS 활성 여부 확인");
//나침반이 나타나도록 설정
googleMap.getUiSettings().setCompassEnabled(true);
// 매끄럽게 이동함
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// API 23 이상이면 런타임 퍼미션 처리 필요
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// 사용권한체크
int hasFineLocationPermission = ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION);
if ( hasFineLocationPermission == PackageManager.PERMISSION_DENIED) {
//사용권한이 없을경우
//권한 재요청
ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
} else {
//사용권한이 있는경우
if ( googleApiClient == null) {
buildGoogleApiClient();
}
if ( ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
googleMap.setMyLocationEnabled(true);
}
}
} else {
if ( googleApiClient == null) {
buildGoogleApiClient();
}
googleMap.setMyLocationEnabled(true);
}
}
private void buildGoogleApiClient()
{
googleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(getActivity(), this)
.build();
googleApiClient.connect();
}
public boolean checkLocationServicesStatus() {
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
@Override
public void onLocationChanged(Location location)
{
Log.i(TAG, "onLocationChanged call..");
searchCurrentPlaces();
}
private void searchCurrentPlaces()
{
@SuppressWarnings("MissingPermission") PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(googleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>(){
@Override
public void onResult(@NonNull PlaceLikelihoodBuffer placeLikelihoods) {
int i = 0;
LikelyPlaceNames = new String[MAXENTRIES];
LikelyAddresses = new String[MAXENTRIES];
LikelyAttributions = new String[MAXENTRIES];
LikelyLatLngs = new LatLng[MAXENTRIES];
for(PlaceLikelihood placeLikelihood : placeLikelihoods) {
LikelyPlaceNames[i] = (String) placeLikelihood.getPlace().getName();
LikelyAddresses[i] = (String) placeLikelihood.getPlace().getAddress();
LikelyAttributions[i] = (String) placeLikelihood.getPlace().getAttributions();
LikelyLatLngs[i] = placeLikelihood.getPlace().getLatLng();
i++;
if(i > MAXENTRIES - 1 ) {
break;
}
}
placeLikelihoods.release();
Location location = new Location("");
location.setLatitude(LikelyLatLngs[0].latitude);
location.setLongitude(LikelyLatLngs[0].longitude);
setCurrentLocation(location, LikelyPlaceNames[0], LikelyAddresses[0]);
}
});
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
@Override
public void onProviderEnabled(String provider)
{
}
@Override
public void onProviderDisabled(String provider)
{
}
@Override
public void onConnected(@Nullable Bundle bundle)
{
if ( !checkLocationServicesStatus()) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("위치 서비스 비활성화");
builder.setMessage("앱을 사용하기 위해서는 위치 서비스가 필요합니다.\n" +
"위치 설정을 수정하십시오.");
builder.setCancelable(true);
builder.setPositiveButton("설정", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent callGPSSettingIntent =
new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(callGPSSettingIntent, GPS_ENABLE_REQUEST_CODE);
}
});
builder.setNegativeButton("취소", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.create().show();
}
LocationRequest locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(UPDATE_INTERVAL_MS);
locationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_MS);
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if ( ActivityCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi
.requestLocationUpdates(googleApiClient, locationRequest, (com.google.android.gms.location.LocationListener) this);
}
} else {
LocationServices.FusedLocationApi
.requestLocationUpdates(googleApiClient, locationRequest, (com.google.android.gms.location.LocationListener) this);
this.googleMap.getUiSettings().setCompassEnabled(true);
this.googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
}
@Override
public void onConnectionSuspended(int i)
{
if ( i == CAUSE_NETWORK_LOST )
Log.e(TAG, "onConnectionSuspended(): Google Play services " +
"connection lost. Cause: network lost.");
else if (i == CAUSE_SERVICE_DISCONNECTED )
Log.e(TAG,"onConnectionSuspended(): Google Play services " +
"connection lost. Cause: service disconnected");
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult)
{
Location location = new Location("");
location.setLatitude(DEFAULT_LOCATION.latitude);
location.setLongitude((DEFAULT_LOCATION.longitude));
setCurrentLocation(location, "위치정보 가져올 수 없음",
"위치 퍼미션과 GPS활성 여부 확인");
}
}