2016-02-10 2 views
1

В настоящее время я работаю над проектом для школы. Я должен использовать службу определения местоположения. У меня проблема с маркером. Я могу найти себя на карте с небольшой точкой из google (я думаю), но маркер всегда на 0,0. Если моя логика хорошая, то getLatitude() и getLongitude() возвращаются NULL. Я следую учебнику для кода.Lat/lgn return 0

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

Я французский, простите за мой плохой английский

ответ

0

Вы должны использовать м енит

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

для получения широты и долготы. В первый раз он будет определенно звонить, а затем он будет звонить, а затем, как только место будет изменено.

Если вы полностью заявляете о том, что у решетки и longi есть шансы, что у ОС нет ничего, она вернет 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(); 
    } 
} 

}