如何在android google maps api V2中获取当前位置?

时间:2014-08-28 18:05:08

标签: java android google-maps

我想在android google maps v2中获取当前位置。这是我的代码:

package android.arin;

import java.util.List;
import location.Location;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import fish.Species;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;

public class MapScreen extends FragmentActivity implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener {

    private Species selectedfish = null;
    private GoogleMap map = null;
    private LocationClient locationClient = null;

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

        setUpScreen();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.map_screen, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        switch (id) {

        }
        return super.onOptionsItemSelected(item);
    }

    private void setUpScreen() {
        selectedfish = (Species) NavigationScreen.FishWhosOptionsClicked;   
        map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        map.setMyLocationEnabled(true);


        List<Location> locations = selectedfish.getLocations();
        for(int i=0; i<locations.size(); i+=1) {
            Location location = locations.get(i);
            LatLng latlong = new LatLng(location.getLatitude(), location.getLongitude());

            map.addMarker(new MarkerOptions()
            .title(location.getAddress())
            .snippet(location.getComment())
            .position(latlong));
        }

        locationClient = new LocationClient(this, this, this);
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnected(Bundle connectionHint) {
        android.location.Location location = locationClient.getLastLocation();

        LatLng latlong = new LatLng(location.getLatitude(), location.getLongitude());
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(latlong, 10));
    }

    @Override
    public void onDisconnected() {
        // TODO Auto-generated method stub

    }
}

但它似乎不起作用。它不会崩溃,但它不会移动到我所在的位置......

有谁知道如何解决这个问题?

感谢。

2 个答案:

答案 0 :(得分:0)

我开发了这个类可以轻松使用GPS,也许它可以帮到你。

您必须仅在根Activity上实例化一个实例并与onStartonStop方法同步,然后您可以从任何类执行静态调用以检索该位置。

//使用

public class MainActivity extends Activity {    

private GPSTracker gpsTracker;

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

    gpsTracker = new GPSTracker(context);
    Location location = GPSTracker.getLocation();
}


@Override
protected void onStart() {
    gpsTracker.connectToApi();
    super.onStart();
}

@Override
protected void onStop() {
    super.onStop();
    if(gpsTracker != null)
        gpsTracker.disconnectToApi();
}

}

// GPSTracker

public class GPSTracker extends Service implements  ConnectionCallbacks, LocationListener, OnConnectionFailedListener {

private static final int MILLISECONDS_PER_SECOND = 1000;
private static final int UPDATE_INTERVAL_IN_SECONDS = 10;
private static final long UPDATE_INTERVAL = MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS;
private static final int FASTEST_INTERVAL_IN_SECONDS = 5;
private static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND * FASTEST_INTERVAL_IN_SECONDS;

private static Context mContext;
private static Location mLocation;
private LocationRequest locationRequest;
private static LocationClient locationClient;
private static boolean isGoogleServiceAvailable;

public GPSTracker(Context context){
    mContext = context;
    locationClient = new LocationClient(mContext, this, this);
    configureLocationRequest();
    connectToApi();
}

public void connectToApi(){
    locationClient.connect();
}

public void disconnectToApi(){
    locationClient.disconnect();
}

private void configureLocationRequest(){
    locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(UPDATE_INTERVAL);
    locationRequest.setFastestInterval(FASTEST_INTERVAL);
}

@Override
public void onConnected(Bundle connectionHint) {
    locationClient.requestLocationUpdates(locationRequest, this);
    isGoogleServiceAvailable = true;
    //Toast.makeText(mContext, "Connected", Toast.LENGTH_SHORT).show();
}

@Override
public void onDisconnected() {  
    isGoogleServiceAvailable = false;
    //Toast.makeText(mContext, "Disconnected", Toast.LENGTH_SHORT).show();
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onLocationChanged(Location location) {
    mLocation = location;
}

@Override
public void onConnectionFailed(ConnectionResult result) {
    isGoogleServiceAvailable = false;
}

public static Location getLocation(){
    //String sourceGPS = "New api current location ->";
    try {
        if(!isGoogleServiceAvailable){
            mLocation = getLastKnownLocationWithDeprecatedApi();
            //sourceGPS = "Old api last know location ->";
        }else if (isCurrentLocationEqualsTodefaultGPSLocation()){
            //sourceGPS = "New api last know location ->";
            mLocation = locationClient.getLastLocation();
        }
    } catch (Exception e) {mLocation = null;}

    if(mLocation == null) {
        mLocation = getDefaultLocation();
        //sourceGPS = "Default location ->";
    }


    return mLocation;
}

private static Location getLastKnownLocationWithDeprecatedApi(){
    LocationManager locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
    Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    return location;
}

private static boolean isCurrentLocationEqualsTodefaultGPSLocation(){
    Location defaultLocation = getDefaultLocation();
    if(mLocation.getLatitude() == defaultLocation.getLatitude()
            && mLocation.getLongitude() == defaultLocation.getLongitude())
        return true;
    else return false;
}

private static Location getDefaultLocation(){
    Location location = new Location("");
    location.setLatitude(39.5693900);
    location.setLongitude(2.6502400);
    return location;
}

}

答案 1 :(得分:-1)

为什么不要求获得位置许可并尝试requestLocationUpdates?

在你的宣言中:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

在您的活动中:

LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 2500f, this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 2500f, this);

然后你只需要实现一个LocationListener:

@Override
public void onLocationChanged(Location location) {
    mLocation = location;
}

我希望这能帮到你!