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; 
    } 
} 

的logcat的錯誤表明,是由61行的IllegalStateException: Not connected

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

GPS在您的設備上已關閉也許?沒有互聯網連接可用? – Stan

+0

@Stan GPS絕對​​開啓,因爲它不會顯示我當前所在位置的藍點。這真的讓我很難過,因爲我可以評論'mLatitude','mLongitude'和'addMarker()'線條,它會完美地打開地圖,在我當前的位置顯示一個藍點。只要我重新註釋這些行,就會發出抱怨沒有連接的錯誤IllegalStateException。 – Jack

+0

我相信,AOS緩存你的上一個位置,以便知道它,你不需要打開GPS系統。所以「GPS肯定會打開,因爲它不會顯示我當前位置的藍點,如果它關閉的話」可能不那麼清楚。此外,我使用定位服務管理當前位置,而不是從地圖中提問。 – Stan

回答

0

我想,如果你有一些第三方的崩潰捕捉SDK使用在您的項目中,如果getCurrentLocation()在以下行中返回null:

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

可能發生SDK捕獲NPE但未能發送報告。的Cuz你的方法getCurrentLocation()可以返回null:

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

看着我logcat的錯誤,我似乎已經忽略了一個建議:

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

因爲這是我的LocationClient請求位置更新,並得到我現在的位置,我移動了我的緯度和經度啓動以及我的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")); 
    }