繁体   English   中英

如何在Android Google Maps API V2中获取当前位置?

[英]How to get current location in android google maps api V2?

我正在尝试获取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

    }
}

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

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

谢谢。

我开发此课程是为了轻松使用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();
}

}

//GPS追踪器

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

}

您为什么不要求位置许可并尝试请求LocationUpdates?

在您的清单中:

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

希望对您有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM