0

지도 앱을 여는 응용 프로그램을 작성 중이며 열린 후 현재 위치에 Marker 개체를 추가하고 싶습니다. 내 애플리케이션이지도 앱을 올바르게 열고 현재 위치의 파란색 점을 표시하지만 Marker을 만들 때 현재 위치를 사용하는 데 문제가 있습니다. 여기 마커에 현재 위치 전달하기

내 소스 코드 :

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.GooglePlayServicesClient; 
import com.google.android.gms.common.GooglePlayServicesUtil; 
import com.google.android.gms.location.LocationClient; 
import com.google.android.gms.location.LocationListener; 
import com.google.android.gms.location.LocationRequest; 
import com.google.android.gms.maps.CameraUpdate; 
import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.MarkerOptions; 
import com.google.android.gms.maps.MapFragment; 
import com.google.android.gms.maps.SupportMapFragment; 
import android.location.Location; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.provider.Settings; 
import android.app.Activity; 
import android.app.Dialog; 
import android.content.Intent; 
import android.support.v4.app.FragmentActivity; 
import android.util.Log; 
import android.widget.Toast; 

public class PlaceMarker extends FragmentActivity 
    implements GooglePlayServicesClient.ConnectionCallbacks, 
    GooglePlayServicesClient.OnConnectionFailedListener, 
    LocationListener { 
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000; 
    private LocationClient mLocationClient = null; 
    private LocationRequest mLocationRequest = null; 
    private GoogleMap mMap; 
    private static final int UPDATE_INTERVAL_IN_SECONDS = 5; 
    private static final int MILLISECONDS_PER_SECOND = 1000; 
    private static final long UPDATE_INTERVAL = MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS; 
    private static final int FASTEST_INTERVAL_IN_SECONDS = 1; 
    private static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND * FASTEST_INTERVAL_IN_SECONDS; 
    private LocationManager locationManager; 
    private Location location = null; 

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

     mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); 
     mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 
     mMap.setMyLocationEnabled(true); 

     mLocationClient = new LocationClient(this, this, this); 
     if (servicesConnected()) { 
      mLocationRequest = LocationRequest.create(); 
      mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
      mLocationRequest.setInterval(UPDATE_INTERVAL); 
      mLocationRequest.setFastestInterval(FASTEST_INTERVAL); 

      Double mLatitude = getCurrentLocation().getLatitude(); 
      Double mLongitude = getCurrentLocation().getLongitude(); 

      mMap.addMarker(new MarkerOptions() 
       .position(new LatLng(mLatitude, mLongitude)) 
       .title("Title Test") 
       .snippet("Snippet Test")); 
     } 
     else { 
      Toast.makeText(this, "Position unavailable", Toast.LENGTH_SHORT).show(); 
     } 
    } 

    @Override 
    protected void onStart() { 
     super.onStart(); 
     mLocationClient.connect(); 
    } 

    @Override 
    protected void onStop() { 
     if (mLocationClient.isConnected()) { 
      mLocationClient.removeLocationUpdates(this); 
     } 
     mLocationClient.disconnect(); 
     super.onStop(); 
    } 

    private Location getCurrentLocation() { 
     Location location = mLocationClient.getLastLocation(); 

     if (location != null) { 
      return location; 
     } 
     else { 
      Toast.makeText(this, "Current Location Unavailable", Toast.LENGTH_SHORT).show(); 
      checkforGPSAndPromptOpen(); 
      return null; 
     } 
    } 

    private void checkforGPSAndPromptOpen() { 
     boolean enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 

     if (!enabled) { 
      Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
      startActivity(intent); 
     } 
    } 

    // Handle results returned to the FragmentActivity by Google Play services 
    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     // Decide what to do based on the original request code 
     switch (requestCode) { 
      case CONNECTION_FAILURE_RESOLUTION_REQUEST : 
      // If the result code is Activity.RESULT_OK, try to connect again 
       switch (resultCode) { 
        case Activity.RESULT_OK : 
        // Try the request again 
        break; 
       } 
      } 
    } 

    private boolean servicesConnected() { 
     // Check that Google Play services is available 
     int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); 

     // If Google Play services is available 
     if (ConnectionResult.SUCCESS == resultCode) { 
      // In debug mode, log the status 
      Log.d("Location Updates", "Google Play services is available."); 
      // Continue 
      return true; 
     // Google Play services was not available for some reason 
     } else { 
      // Get the error code 
      // Get the error dialog from Google Play services 
      Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(resultCode, this, CONNECTION_FAILURE_RESOLUTION_REQUEST); 

      // If Google Play services can provide an error dialog 
      if (errorDialog != null) { 
       errorDialog.show(); 
      } 
      return false; 
     } 
    } 

    /* 
    * Called by Location Services when the request to connect the client finishes successfully. 
    * At this point, you can request the current location or start periodic updates 
    */ 
    @Override 
    public void onConnected(Bundle dataBundle) { 
     // Display the connection status 
     Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show(); 
     mLocationClient.requestLocationUpdates(mLocationRequest, this); 
     location = getCurrentLocation(); 
     takeToLocation(convertLocationtoLatLong(location)); 
    } 

    /* 
    * Called by Location Services if the connection to the location client drops because of an error. 
    */ 
    @Override 
    public void onDisconnected() { 
     // Display the connection status 
     Toast.makeText(this, "Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show(); 
    } 

    public void onLocationChanged(Location location) { 
     // Report to the UI that the location was updated 
//  String msg = "Updated location: " + Double.toString(location.getLatitude()) + "," + Double.toString(location.getLongitude()); 
//  Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); 
    } 

    /* 
    * Called by Location Services if the attempt to Location Services fails. 
    */ 
    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 

    } 

    private void takeToLocation(LatLng newLocation) { 
     if (newLocation != null) { 
      CameraUpdate update = CameraUpdateFactory.newLatLngZoom(newLocation, 16); 
      mMap.animateCamera(update); 
     } 
     else { 
      Toast.makeText(this, "Position unavailable", Toast.LENGTH_SHORT).show(); 
     } 
    } 
    private LatLng convertLocationtoLatLong(Location location) { 
     LatLng currentLatLong = new LatLng(location.getLatitude(), location.getLongitude()); 
     return currentLatLong; 
    } 
} 

로그 캣 오류가 라인 (61)에 의해 발생하는 IllegalStateException: Not connected이 있음을 보여줍니다

Double mLatitude = getCurrentLocation().getLatitude(); 
+0

기기에서 GPS가 꺼져있을 수 있습니다. 인터넷에 연결할 수 없습니까? – Stan

+0

@Stan GPS가 켜져 있으면 현재 위치에서 파란색 점이 표시되지 않으므로 확실히 켜져 있습니다. 이것은 'mLatitude','mLongitude','addMarker()'라인을 주석 처리 할 수 ​​있기 때문에 정말로 저를 곤두박질 쳤습니다. 현재의 위치에 파란색 점이 찍힌 맵을 완벽하게 열어줍니다. 내가 다시 그 라인을 주석으로, 나는'IllegalStateException' 오류가 연결에 대해 불평 얻을. – Jack

+0

나는 AOS가 당신의 마지막 위치를 캐시해서 GPS 시스템을 켜야 할 필요가 없다는 것을 알고 있다고 믿는다. 따라서 "GPS가 켜져있는 경우 현재 위치에서 파란색 점이 표시되지 않으므로 GPS가 켜져 있습니다."라는 메시지가 분명하지 않을 수 있습니다. 또한지도에서 요청하는 대신 위치 서비스를 사용하여 현재 위치를 관리했습니다. – Stan

답변

0

사용한 SDK를 잡기 일부 타사 충돌이있는 경우 같아요 다음 프로젝트에서 getCurrentLocation()이 다음 줄에 null을 반환하는 경우 :

Double mLatitude = getCurrentLocation().getLatitude(); 
    Double mLongitude = getCurrentLocation().getLongitude(); 

SDK가 NPE를 포착했지만 보고서를 보내지 못할 수 있습니다. 당신의 방법 getCurrentLocation()가 null을 반환 할 수 사촌이이기 때문에

Not connected. Call connect() and wait for onConnected() to be called. 

내 LocationClient이 위치 업데이트를 요청하고 가져옵니다 내 로그 캣 오류를 보면

Toast.makeText(this, "Current Location Unavailable", Toast.LENGTH_SHORT).show(); 
    checkforGPSAndPromptOpen(); 
    return null; 
0

을, 나는 제안을 간과 한 듯 내 현재 위치, 위도 및 경도 시작뿐만 아니라이 방법 내 내 addMarker() 코드를 이동했습니다.

public void onConnected(Bundle dataBundle) { 
     // Display the connection status 
     Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show(); 
     mLocationClient.requestLocationUpdates(mLocationRequest, this); 
     location = getCurrentLocation(); 
     takeToLocation(convertLocationtoLatLong(location)); 

     Double mLatitude = getCurrentLocation().getLatitude(); 
     Double mLongitude = getCurrentLocation().getLongitude(); 

     mMap.addMarker(new MarkerOptions() 
      .position(new LatLng(mLatitude, mLongitude)) 
      .title("Title Test") 
      .snippet("Snippet Test")); 
    }