2017-12-12 5 views
1

지도에서 현재 업데이트 된 위치를 표시하려고합니다.Google지도로 업데이트 된 현재 위치를 표시하는 방법

내가지도와 위치를 확대하면 축소 한 다음 위치를 표시합니다. 동일한 줌 위치에서 업데이트 된 위치를 표시하지 않습니다. 위치 업데이트를 마친 후지도에서 마커를 다시 설정합니다. 맵에서 마커를 설정하는 데 문제가 있다고 생각합니다. 지도에 현재 업데이트 된 위치를 표시해주세요. onLocationChanged가 다음 트리거

public class MainActivity extends FragmentActivity implements OnMapReadyCallback , GoogleApiClient.ConnectionCallbacks, 
    GoogleApiClient.OnConnectionFailedListener, LocationListener { 

GoogleMap googleMa; 
double latitude; 
private GoogleApiClient mGoogleApiClient; 
double longitude; 
private Location mLastLocation = null; 
private LocationRequest mLocationRequest; 
String mPermission = android.Manifest.permission.ACCESS_FINE_LOCATION; 
protected LocationManager locationManager; 

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

    ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 
      2); 

    locationManager = (LocationManager) MainActivity.this 
      .getSystemService(Context.LOCATION_SERVICE); 
    boolean isGPSEnabled = locationManager 
      .isProviderEnabled(LocationManager.GPS_PROVIDER); 

    if (checkPlayServices()) { 

     buildGoogleApiClient(); 
     createLocationRequest(); 
     displayLocation(); 

    } 
    initailizeMap(); 
} 

public void initailizeMap() { 
    if (googleMa == null) { 
     SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 
     mapFragment.getMapAsync(this); 
    } 
} 

@Override 
public void onMapReady(GoogleMap googleMap) { 
    googleMa = googleMap; 
    Log.d("aaaaaa", " on map --->" + latitude + " " + longitude); 
    displayLocation(); 

} 

public void displayLocation() { 
    try { 
     GPSTracker gps = new GPSTracker(MainActivity.this); 
     if (gps.canGetLocation()) { 
      latitude = gps.getLatitude(); 
      longitude = gps.getLongitude(); 
      Toast.makeText(getApplicationContext(), "Latitude: " + latitude + " Longitude: " + longitude, Toast.LENGTH_LONG).show(); 
      final LatLng loc = new LatLng(latitude, longitude); 
      Marker ham = googleMa.addMarker(new MarkerOptions().position(loc).title("This is Me").icon(BitmapDescriptorFactory.fromResource(R.drawable.greenpointer))); 
      googleMa.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15)); 
     } 
    } catch (Exception e) { 
    } 
} 

@Override 
public void onConnectionFailed(ConnectionResult result) { 
    Log.i("aaaaaaaa", "Connection failed: ConnectionResult.getErrorCode() = " 
      + result.getErrorCode()); 
} 

@Override 
public void onConnected(Bundle arg0) { 
    startLocationUpdates(); 
} 

@Override 
public void onConnectionSuspended(int arg0) { 
    mGoogleApiClient.connect(); 
} 

@Override 
public void onLocationChanged(Location location) { 
    mLastLocation = location; 
    Log.d("aaaaaaaa===>", "" + String.valueOf(location.getLatitude()) + "\n" + String.valueOf(location.getLongitude())); 
    Toast.makeText(getApplicationContext(), "Location changed!", 
      Toast.LENGTH_SHORT).show(); 
    displayLocation(); 
} 

private boolean checkPlayServices() { 

    GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance(); 

    int resultCode = googleApiAvailability.isGooglePlayServicesAvailable(this); 

    if (resultCode != ConnectionResult.SUCCESS) { 
     if (googleApiAvailability.isUserResolvableError(resultCode)) { 
      googleApiAvailability.getErrorDialog(this, resultCode, 
        1000).show(); 
     } else { 
      Toast.makeText(getApplicationContext(), 
        "This device is not supported.", Toast.LENGTH_LONG) 
        .show(); 
      finish(); 
     } 
     return false; 
    } 
    return true; 
} 

protected synchronized void buildGoogleApiClient() { 
    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API).build(); 

    mGoogleApiClient.connect(); 

    LocationRequest mLocationRequest = new LocationRequest(); 
    mLocationRequest.setInterval(100); 
    mLocationRequest.setFastestInterval(500); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() 
      .addLocationRequest(mLocationRequest); 

    PendingResult<LocationSettingsResult> result = 
      LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); 

    result.setResultCallback(new ResultCallback<LocationSettingsResult>() { 
     @Override 
     public void onResult(LocationSettingsResult locationSettingsResult) { 

      final Status status = locationSettingsResult.getStatus(); 

      switch (status.getStatusCode()) { 
       case LocationSettingsStatusCodes.SUCCESS: 
        break; 
       case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: 
        try { 
         status.startResolutionForResult(MainActivity.this, 2000); 

        } catch (IntentSender.SendIntentException e) { 
        } 
        break; 
       case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: 
        break; 
      } 
     } 
    }); 
} 

protected void createLocationRequest() { 
    mLocationRequest = new LocationRequest(); 
    mLocationRequest.setInterval(10000); // 10 sec 
    mLocationRequest.setFastestInterval(5000); // 5 sec 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    mLocationRequest.setSmallestDisplacement(10); // 10 meters 
} 

protected void startLocationUpdates() { 
    LocationServices.FusedLocationApi.requestLocationUpdates(
      mGoogleApiClient, mLocationRequest, this); 
} 

protected void stopLocationUpdates() { 
    LocationServices.FusedLocationApi.removeLocationUpdates(
      mGoogleApiClient, this); 
} 

@Override 
protected void onDestroy() { 
    super.onDestroy(); 
    stopLocationUpdates(); 
} 

}

답변

2

후 내가 GPSTracker, 아니 코드입니다 모르겠어요 (gps에서 location 인스턴스가 아닌에서 latitudelongitude를 가져 오기 위해 필요하지만, 확실히 당신이 업데이트 포기하지 않을 것 위도, 경도)

@Override 
public void onLocationChanged(Location location) { 
    mLastLocation = location; 
    // use latitude and longitude given by 
    // location.getLatitude(), location.getLongitude() 
    // for updated location marker 
    Log.d("aaaaaaaa===>", "" + location.getLatitude() + "\n" + location.getLongitude()); 
    // displayLocation(); 

    // to remove old markers 
    googleMa.clear(); 
    final LatLng loc = new LatLng(location.getLongitude(), location.getLongitude()); 

    Marker ham = googleMa.addMarker(new MarkerOptions().position(loc).title("This is Me").icon(BitmapDescriptorFactory.fromResource(R.drawable.greenpointer))); 
    googleMa.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15)); 
} 
+0

위치 변경 기능에서 마커를 사용했지만 여러 마커가 표시 될 때 위치 변경 전화 교환 –

+0

@DeepakSh arma 오, 당신은 오래된 마커를 지울 필요가, 나는 거기에 함수'googleMa.clear()'또는 뭔가있을 것 같아요. 마커를 추가하기 전에 이것을 호출하십시오. –

+0

감사합니다. 잘 작동합니다. –