2016-05-29 5 views
0

Я хочу добавить карту google с текущим местоположением. Как я могу это сделать? Я нашел этот код, но место статично. Как я могу это исправить?Текущее местоположение с android

public class MapFragment extends Fragment implements OnMapReadyCallback { 
    SupportMapFragment mSupportMapFragment; 
    private GoogleMap mMap; 
    int ZOOM_LEVEL=15; 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View mTrackView = inflater.inflate(R.layout.fragment_map, container, false); 
     mSupportMapFragment = SupportMapFragment.newInstance(); 
     FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction(); 
     fragmentTransaction.add(R.id.mapwhere, mSupportMapFragment); 
     fragmentTransaction.commit(); 
     return mTrackView; 
    } 
    @Override 
    public void onMapReady(GoogleMap map) { 
     //googleMap = mMap; 
     setUpMapIfNeeded(); 
    } 
    public void onStart() { 
     // TODO Auto-generated method stub 
     super.onStart(); 
     if(mSupportMapFragment!=null){ 
      googleMap = mSupportMapFragment.getMap(); 
      if(googleMap!=null){ 
       googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 
       googleMap.getUiSettings().setMyLocationButtonEnabled(false); 
       googleMap.setMyLocationEnabled(false); 
       CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
         new LatLng(12.12122, 
           17.22323), ZOOM_LEVEL); 
       googleMap.animateCamera(cameraUpdate); 
      } 
     } 
    } 
} 
+0

Вы должны были сделать некоторый поиск по StackOverflow, прежде чем задавать этот вопрос, но для справки http://stackoverflow.com/questions/1513485/how-do-i- get-the-current-gps-location-programatically-in-android – iYoung

+0

Возможный дубликат [Что такое самый простой и самый надежный способ получить текущее местоположение пользователя на Android?] (http://stackoverflow.com/questions/3145089/что-это-The-Простейшие-и-самый надежный способ-к-получить пользователь-ток-местоположение-на-а) – iYoung

ответ

0

Попробуйте

private void displayLocation() { 

    LocationRequest locationRequest = LocationRequest.create(); 
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    locationRequest.setInterval(30 * 1000); 
    locationRequest.setFastestInterval(5 * 1000); 
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() 
      .addLocationRequest(locationRequest); 

    // ************************** 
    builder.setAlwaysShow(true); // this is the key ingredient 

    // ************************** 
    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi 
      .checkLocationSettings(mGoogleApiClient, builder.build()); 
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() { 
     @Override 
     public void onResult(LocationSettingsResult result) { 
      final Status status = result.getStatus(); 
      final LocationSettingsStates state = result.getLocationSettingsStates(); 
      switch (status.getStatusCode()) { 
       case LocationSettingsStatusCodes.SUCCESS: 

        // All location settings are satisfied. The client can 
        // initialize location 
        // requests here. 
        AlertDialog.Builder dialog = new AlertDialog.Builder(context); 
        dialog.setMessage(context.getResources().getString(R.string.allow_location)); 
        dialog.setPositiveButton(context.getResources().getString(R.string.yes), 
          new DialogInterface.OnClickListener() { 
           @Override 
           public void onClick(DialogInterface paramDialogInterface, int paramInt) { 
            progressDialog = Utility.getProgressDialog(context); 
            progressDialog.setCanceledOnTouchOutside(false); 
            progressDialog.setCancelable(false); 

            if (progressDialog != null) { 
             progressDialog.show(); 
            } 

             final Handler handler = new Handler(); 
             handler.postDelayed(new Runnable() { 
              @Override 
              public void run() { 
               // Do something after 5s = 5000ms 
               progressDialog.dismiss(); 
               Location mLastLocation = LocationServices.FusedLocationApi 
                 .getLastLocation(mGoogleApiClient); 
               if (mLastLocation != null) { 
                setUpMap(mLastLocation.getLatitude(), mLastLocation.getLongitude(), "Current Location", 
                  true); 
               } 
              } 
             }, 4000); 



           } 
          }); 
        dialog.setNegativeButton(context.getString(R.string.no), new DialogInterface.OnClickListener() { 

         @Override 
         public void onClick(DialogInterface paramDialogInterface, int paramInt) { 
          setUpMap(12.9667, 77.5667, "", false); 
          Utility.showToat(context, "Select Address from the Map"); 
         } 
        }); 
        dialog.setCancelable(false); 
        dialog.show(); 

        break; 
       case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: 
        // Location settings are not satisfied. But could be fixed 
        // by showing the user 
        // a dialog. 
        try { 
         // Show the dialog by calling 
         // startResolutionForResult(), 
         // and check the result in onActivityResult(). 
         status.startResolutionForResult(GoogleMapActivity.this, REQUEST_CHECK_SETTINGS); 
        } catch (IntentSender.SendIntentException e) { 
         // Ignore the error. 
        } 
        break; 
       case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: 
        // Location settings are not satisfied. However, we have no 
        // way to fix the 
        // settings so we won't show the dialog. 
        break; 
      } 
     } 
    }); 

} 
Смежные вопросы