2017-02-09 53 views
0

我想縮放在谷歌地圖android當前位置的相機,但我的代碼不工作我已經嘗試了很多方法我的gps位置是在手機上此代碼在模擬器上工作但不是在設備工作我已經嘗試onLocationChanged方法也請任何好友建議我適當可行的解決方案當前位置更新在谷歌地圖上的編碼不工作在android

   mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
       mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 
         0, mLocationListener); 
       Criteria mCriteria = new Criteria(); 
       String bestProvider = String.valueOf(mLocationManager.getBestProvider(mCriteria, true)); 
       Location mLocation = mLocationManager.getLastKnownLocation(bestProvider); 
       if (mLocation != null) { 
        Log.e("TAG", "GPS is on"); 
        final double currentLatitude = mLocation.getLatitude(); 
        final double currentLongitude = mLocation.getLongitude(); 
        LatLng loc1 = new LatLng(currentLatitude, currentLongitude); 

        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentLatitude, currentLongitude), 10)); 
        mMap.animateCamera(CameraUpdateFactory.zoomTo(10), 1000, null); 
+0

你可以試試這個'mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000 * 60 * 1, 10,mLocationListener);'?並讓我知道你在得到什麼 –

+0

雅確定我會盡力讓你知道 – user3269550

+0

這已經發生在我身上。如果「mLocation」爲空,請立即轉到設備上的Google地圖,查看地圖是否能夠獲取某個位置,如果地圖不顯示當前位置,則表示設備存在問題。重新啓動設備解決了我的問題。 –

回答

0

替換:

mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentLatitude, currentLongitude), 10)); 

有了:

mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc1, 10)); 
+0

但位置總是返回空 – user3269550

+0

您是否要求Manifest提供ACCESS_FINE_LOCATION權限? – tahsinRupam

+0

是的,我已經要求ACCESS_FINE_LOCATION和ACCESS_COARSE_LOCATION – user3269550

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

    mGoogleApiClient.connect(); 
} 

mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 

CameraPosition cameraPosition = new CameraPosition.Builder() 
      .target(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude())) 
      .zoom(10) 
      .bearing(0.0f) 
      .tilt(00.0f) 
      .build(); 
    map.moveCamera(CameraUpdateFactory 
      .newCameraPosition(cameraPosition)); 
1

幾個小時後,我做了一個課,實時跟蹤GPS。 首先,這個類添加到您的項目

public class GPSTracker implements LocationListener { 


private final Activity mContext; 

// flag for GPS status 
boolean isGPSEnabled = false; 

// flag for network status 
boolean isNetworkEnabled = false; 

// flag for GPS status 
boolean canGetLocation = false; 

Location location; // location 
double latitude; // latitude 
double longitude; // longitude 

// The minimum distance to change Updates in meters 
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters 

// The minimum time between updates in milliseconds 
private static final long MIN_TIME_BW_UPDATES = 1000*60; // 1 minute 

// Declaring a Location Manager 
protected LocationManager locationManager; 

private LocationCallbackListener mCallbackListener; 

public GPSTracker(Activity context, LocationCallbackListener callbackListener) { 
    this.mContext = context; 
    this.mCallbackListener = callbackListener; 
    getLocation(); 
} 

public Location getLocation() { 
    try { 
     locationManager = (LocationManager) mContext 
       .getSystemService(LOCATION_SERVICE); 

     // getting GPS status 
     isGPSEnabled = locationManager 
       .isProviderEnabled(LocationManager.GPS_PROVIDER); 

     // getting network status 
     isNetworkEnabled = locationManager 
       .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     if (!isGPSEnabled && !isNetworkEnabled) { 
      // no network provider is enabled 
     } else { 

      // First get location from Network Provider 
      if (isNetworkEnabled) { 
       locationManager.requestLocationUpdates(
         LocationManager.NETWORK_PROVIDER, 
         MIN_TIME_BW_UPDATES, 
         MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
       Log.d("Network", "Network"); 
       if (locationManager != null) { 
        location = locationManager 
          .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 

        if (location != null) { 
         latitude = location.getLatitude(); 
         longitude = location.getLongitude(); 
        } 
       } 
       this.canGetLocation = true; 
      }else { 
       this.canGetLocation = false; 
      } 
      // if GPS Enabled get lat/long using GPS Services 
      if (isGPSEnabled) { 
       this.canGetLocation = true; 
       if (location == null) { 
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED 
          && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
         // TODO: Consider calling 
         // ActivityCompat#requestPermissions 
         // here to request the missing permissions, and then overriding 
         // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
         //           int[] grantResults) 
         // to handle the case where the user grants the permission. See the documentation 
         // for ActivityCompat#requestPermissions for more details. 

         locationManager.requestLocationUpdates(
           LocationManager.GPS_PROVIDER, 
           MIN_TIME_BW_UPDATES, 
           MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
         Log.d("GPS Enabled", "GPS Enabled"); 
         if (locationManager != null) { 
          location = locationManager 
            .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
          if (location != null) { 
           latitude = location.getLatitude(); 
           longitude = location.getLongitude(); 
          } 


         } 
        } 
       } 
      }else { 
       this.canGetLocation = false; 
      } 
     } 

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

    return location; 
} 

/** 
* Stop using GPS listener 
* Calling this function will stop using GPS in your app 
* */ 
public void stopUsingGPS() { 
    if (locationManager != null) { 
     if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      // TODO: Consider calling 
      // ActivityCompat#requestPermissions 
      // here to request the missing permissions, and then overriding 
      // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
      //           int[] grantResults) 
      // to handle the case where the user grants the permission. See the documentation 
      // for ActivityCompat#requestPermissions for more details. 
      locationManager.removeUpdates(GPSTracker.this); 
     } 

    } 
} 

/** 
* Function to get latitude 
* */ 
public double getLatitude(){ 
    if(location != null){ 
     latitude = location.getLatitude(); 
    } 

    // return latitude 
    return latitude; 
} 

/** 
* Function to get longitude 
* */ 
public double getLongitude(){ 
    if(location != null){ 
     longitude = location.getLongitude(); 
    } 

    // return longitude 
    return longitude; 
} 

/** 
* Function to check GPS/wifi enabled 
* @return boolean 
* */ 
public boolean canGetLocation() { 
    return this.canGetLocation; 
} 

/** 
* Function to show settings alert dialog 
* On pressing Settings button will lauch Settings Options 
* */ 
public void showSettingsAlert(){ 
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 

    // Setting Dialog Title 
    alertDialog.setTitle("GPS is settings"); 

    // Setting Dialog Message 
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?"); 

    // On pressing Settings button 
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 
      Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
      mContext.startActivity(intent); 
     } 
    }); 

    // on pressing cancel button 
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 
      dialog.cancel(); 
     } 
    }); 

    // Showing Alert Message 
    alertDialog.show(); 
} 

@Override 
public void onLocationChanged(Location location) { 
    mCallbackListener.onChangeLocation(location.getLatitude(),location.getLongitude()); 
} 

@Override 
public void onStatusChanged(String s, int i, Bundle bundle) { 

} 

@Override 
public void onProviderEnabled(String s) { 

} 

@Override 
public void onProviderDisabled(String s) { 

}} 

在您的片段或活動,聲明它的MapView的初始化旁邊是這樣的:

public GPSTracker mGPS; 
mGPS = new GPSTracker(mActivity, new LocationCallbackListener() { 
      @Override 
      public void onChangeLocation(double latitude, double longitude) { 

      } 
     }); 

每當你的位置被改變,它將在onChangeLocation()重寫方法更新。

紅利 如果您想訪問您當前的緯度,經度。只需撥打電話 mGPS.getLatitude();mGPS.getLongitude();

希望這個能幫助您進一步瞭解更多。

相關問題