【问题标题】:Lat/lgn return 0纬度/lgn 返回 0
【发布时间】:2016-02-10 18:43:21
【问题描述】:

我目前正在为学校做一个项目。我必须使用定位服务。我有一个标记问题。我可以用谷歌的一个小点在地图上定位自己(我认为),但标记总是在 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;
    }
}

我是法国人,对不起我的英语不好

【问题讨论】:

    标签: java android google-maps gps geolocation


    【解决方案1】:

    你应该使用方法

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

    获取纬度和经度。第一次它肯定会被调用,然后它会被调用,然后一旦位置发生变化。

    如果你强制要求 latti 和 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();
        } 
    } 
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-01
      • 2011-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多