将当前位置传递给Marker

时间:2014-02-05 23:12:13

标签: android google-maps google-maps-android-api-2 android-maps android-maps-v2

我正在编写一个打开地图应用的应用程序,我希望能够在打开时在当前位置添加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();

2 个答案:

答案 0 :(得分:0)

我想如果您的项目中使用了第三方崩溃捕获SDK,那么getCurrentLocation()会在以下行中返回null:

    Double mLatitude = getCurrentLocation().getLatitude();
    Double mLongitude = getCurrentLocation().getLongitude();
可能会发生SDK捕获NPE但无法发送报告。因为你的方法getCurrentLocation()可以返回null:

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

答案 1 :(得分: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"));
    }