Lat / lgn返回0

时间:2016-02-10 18:43:21

标签: java android google-maps gps geolocation

我目前正在为学校做项目。我必须使用位置服务。我有一个标记问题。我可以通过谷歌(我认为)中的一个小点找到自己在地图上,但标记总是在0,0。如果我的逻辑良好,getLatitude()getLongitude()返回NULL。我已经按照代码的教程。

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    GPSTracker gps;
    //ImageItem imgItem;
    double lat;
    double longi;
    double latitude;
    double longitude;
    String adresse;

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

    public void laCreation() {
        gps = new GPSTracker(MapsActivity.this);

        if (gps.canGetLocation()==true) {

            latitude = gps.getLatitude();
            longitude = gps.getLongitude();
            lat = latitude;
            longi =  longitude;
        } else {
            gps.showSettingsAlert();
        }
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        mMap = mapFragment.getMap();
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
       
        }
        mMap.setMyLocationEnabled(true);
        LatLng position = new LatLng(lat, longi);
        mMap.addMarker(new MarkerOptions().position(position).title("Vous : "+ latitude + ","+longitude +"," +adresse));//new LatLng(lat,longi)
        mMap.moveCamera(CameraUpdateFactory.newLatLng(position));
    }
    
    public void onMapReady(GoogleMap googleMap) {}
}

这是我的GPSTracker:

public class GPSTracker extends Service implements LocationListener {

    private final Context context;

    boolean isGPSEnabled = false;
    boolean isNetworkEnabled = false;
    boolean canGetLocation = false;

    Location location;

    double latitude;
    double longitude;

    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;  //10m avant update gps
    private static final long MIN_TIME_BW_UPDATES = 2000;   //2 sec avant uptade gps

    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.context = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
            } else {
                this.canGetLocation = true;
                onLocationChanged(location);


                if (isGPSEnabled) {                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                            if (latitude ==0){showSettingsAlert();}
                        }
                    }
                }

                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                            if (latitude ==0){showSettingsAlert();}
                        }
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return location;
    }

    public void stopUsingGPS() {
        if (locationManager != null) {
            }
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    @Override
    public void onLocationChanged(Location location) {

    // TODO Auto-generated method stub
    }


    public double getLatitude(){

        if(location != null){
            latitude = location.getLatitude();
        }
        return latitude;
    }

    public double getLongitude(){
        if(location != null){

            longitude = location.getLongitude();
        }
        return longitude;
    }

    public boolean canGetLocation(){

        return this.canGetLocation;
    }

    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
        alertDialog.setTitle("GPS en cours de configuration");
        alertDialog.setMessage("GPS non valide. Voulez-vous aller dans le menu de configuration?");
        alertDialog.setPositiveButton("Configuration", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                context.startActivity(intent);
            }
        });
        alertDialog.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        alertDialog.show();
    }

    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
}

我是法国人,抱歉我的英语不好

1 个答案:

答案 0 :(得分:0)

你应该使用方法

   @Override 
   public void onLocationChanged(Location location) { 
        Log.i(TAG, location.getLatitude()+"-"+longitude = location.getLongitude());
      // TODO Auto-generated method stub 
    }

获取经度和纬度。第一次它将获得肯定的呼叫,然后它将被呼叫,然后一旦位置改变。

如果你强迫要求latti和longi他们有机会OS没有任何东西它会返回0,0。


还有一种方法是使用GoogleFuseLocationApi

询问最后的已知位置
 public class SpotRecognistionService extends Service {


private static final String TAG = SpotRecognistionService.class.getSimpleName();
public static final String NOTIFICATION = "location.track.services.receiver";


//Google Api Client for Location 
private GoogleApiClient mGoogleApiClient;


// private Location mLastLocation; 
private LocationRequest mLocationRequest;
private GPSLocationListener gpsLocationListener;


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


protected synchronized void buildGoogleApiClient() { 
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(gpsLocationListener)
            .addOnConnectionFailedListener(gpsLocationListener)
            .addApi(LocationServices.API) 
            .build(); 
} 


@Override 
public void onCreate() { 
    super.onCreate(); 
    Log.i(TAG, "Service creating");


    gpsLocationListener = new GPSLocationListener();
    buildGoogleApiClient(); 


    //Connect  to get Location 
    mGoogleApiClient.connect();
} 


@Override 
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i(TAG, "onStartCommand()");
    return super.onStartCommand(intent, flags, startId);
} 


@Override 
public void onDestroy() { 
    super.onDestroy(); 
    Log.i(TAG, "Service destroying");
    if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
        mGoogleApiClient.disconnect();
} 


private class GPSLocationListener implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {


    @Override 
    public void onLocationChanged(Location location) {


        if (location != null) {
        //Update Result 
        publishResults(location.toString(), 1);
    } 


    private void publishResults(String lat_Long, int result) {
       Log.i(TAG, lat_Long);
    } 


    @Override 
    public void onConnected(Bundle bundle) {
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(10000);


        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    } 


    @Override 
    public void onConnectionSuspended(int i) {
        reConnect(); 
    } 


    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) {
        reConnect(); 
    } 


    public void reConnect() { 
        if (mGoogleApiClient != null && !mGoogleApiClient.isConnected())
            mGoogleApiClient.connect();
    } 
} 

}