处理位置更新

时间:2014-04-21 15:46:44

标签: android google-maps

我正在尝试创建一个将使用Google地图支出竞赛电路的网页,并使用某种点来显示和更新用户的当前位置。

我的代码是:

public class TopGearLocationTracker extends FragmentActivity implements
//Specifies methods that Location Services calls when a location client 
//is connected or disconnected.//
GooglePlayServicesClient.ConnectionCallbacks,
//Specifies a method that Location Services calls if an error occurs while
//attempting to connect the location client. This method uses the previously-
//defined showErrorDialog method to display an error dialog that attempts to 
//fix the problem using Google Play services.
GooglePlayServicesClient.OnConnectionFailedListener,
//The callback method that Location Services invokes to send a location update 
//to your application is specified in the LocationListener interface, in the method 
//onLocationChanged(). The incoming argument is a Location object containing the 
//location's latitude and longitude. The following snippet shows how to specify 
//the interface and define the method:
LocationListener
{
    // Global constants
    /*
     * Define a request code to send to Google Play services
     * This code is returned in Activity.onActivityResult
     */
    private final static int
            CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;


    // Global variable to hold the current location
    Location mCurrentLocation;
    private GoogleMap aMap;


    // Global constants
    // Milliseconds per second
    private static final int MILLISECONDS_PER_SECOND = 1000;
    // Update frequency in seconds
    public static final int UPDATE_INTERVAL_IN_SECONDS = 5;
    // Update frequency in milliseconds
    private static final long UPDATE_INTERVAL =
            MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS;
    // The fastest update frequency, in seconds
    private static final int FASTEST_INTERVAL_IN_SECONDS = 1;
    // A fast frequency ceiling in milliseconds
    private static final long FASTEST_INTERVAL =
            MILLISECONDS_PER_SECOND * FASTEST_INTERVAL_IN_SECONDS;

    // Define an object that holds accuracy and frequency parameters
    LocationRequest mLocationRequest;


    // Global variables
    LocationClient mLocationClient;
    boolean mUpdatesRequested;

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

        // Set the map up
        // Set the map to Top Gear track location
        LatLng topGearTrack = new LatLng(51.116492, -0.541767);

        aMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

        aMap.getUiSettings().setAllGesturesEnabled(false);
        aMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        aMap.setMyLocationEnabled(true);
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(topGearTrack, 15));

        setUpMapIfNeeded();

        // Create the LocationRequest object
        mLocationRequest = LocationRequest.create();
        // Use high accuracy
        mLocationRequest.setPriority(
                LocationRequest.PRIORITY_HIGH_ACCURACY);
        // Set the update interval to 5 seconds
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        // Set the fastest update interval to 1 second
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);

        // Open the shared preferences
        //mPrefs = getSharedPreferences("SharedPreferences",
                //Context.MODE_PRIVATE);
        // Get a SharedPreferences editor
        //mEditor = mPrefs.edit();

        /*
         * Create a new location client, using the enclosing class to
         * handle callbacks.
         */
        mLocationClient = new LocationClient(this, this, this);
        // Start with updates turned off
        mUpdatesRequested = false;   
    }

    public void setUpMapIfNeeded() 
    {
        //Do a null check to confirm that we have not already instantiated the map.
        if (aMap == null) 
        {
            aMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
                   .getMap();
        //Check if we were successful in obtaining the map.
        if (aMap != null) 
        {
            //The Map is verified. It is now safe to manipulate the map.
            }
        }
    }

    /*
     * Called when the Activity becomes visible.
     */
    @Override
    protected void onStart() 
    {
        super.onStart();
        // Connect the client.
        mLocationClient.connect();
    }

    /*
     * Called when the Activity is no longer visible.
     */
    @Override
    protected void onStop() 
    {
        // Disconnecting the client invalidates it.
        mLocationClient.disconnect();
        super.onStop();
    }


    // *************** CHECK FOR GOOGLE PLAY SERVICES *************** //


    @SuppressWarnings("unused")
    private boolean servicesConnected() 
    {
        // Check that Google Play services is available
        int resultCode =
                GooglePlayServicesUtil.
                        isGooglePlayServicesAvailable(this);
        // If Google Play services is available
        if (ConnectionResult.SUCCESS == resultCode) 
        {
            // In debug mode, log the status
            Log.d("Location Updates",
                    "Google Play services is available.");
            // Continue
            return true;
        // Google Play services was not available for some reason
        } 
        else 
        {
            // Get the error code
            // Get the error dialog from Google Play services
            Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
                    resultCode,
                    this,
                    CONNECTION_FAILURE_RESOLUTION_REQUEST);
            // If Google Play services can provide an error dialog
            if (errorDialog != null) 
            {
                // Create a new DialogFragment for the error dialog
                ErrorDialogFragment errorFragment =
                        new ErrorDialogFragment();
                // Set the dialog in the DialogFragment
                errorFragment.setDialog(errorDialog);
                // Show the error dialog in the DialogFragment
                errorFragment.show(getSupportFragmentManager(),
                        "Location Updates");
            }
        }
        return false;
    }


    // Define a DialogFragment that displays the error dialog
    public static class ErrorDialogFragment extends DialogFragment 
    {
        // Global field to contain the error dialog
        private Dialog mDialog;
        // Default constructor. Sets the dialog field to null
        public ErrorDialogFragment() 
        {
            super();
            mDialog = null;
        }
        // Set the dialog to display
        public void setDialog(Dialog dialog) 
        {
            mDialog = dialog;
        }
        // Return a Dialog to the DialogFragment.
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) 
        {
            return mDialog;
        }
    }

    /*
     * Handle results returned to the FragmentActivity
     * by Google Play services
     */
    @Override
    protected void onActivityResult(
            int requestCode, int resultCode, Intent data) 
    {
        // Decide what to do based on the original request code
        switch (requestCode) 
        {
            case CONNECTION_FAILURE_RESOLUTION_REQUEST :
            /*
             * If the result code is Activity.RESULT_OK, try
             * to connect again
             */
                switch (resultCode) {
                    case Activity.RESULT_OK :
                    /*
                     * Try the request again
                     */
                    break;
                }
        }
    }


    // ******************** CALLBACK METHODS AND INTERFACES ******************** //


    /*
     * Called by Location Services when the request to connect the
     * client finishes successfully. At this point, you can
     * request the current location or start periodic updates
     */
    @Override
    public void onConnected(Bundle dataBundle) 
    {
        // Display the connection status
        Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
        // If already requested, start periodic updates
        if (mUpdatesRequested) 
        {
            mLocationClient.requestLocationUpdates(mLocationRequest, this);
        }
    }

    /*
     * Called by Location Services if the connection to the
     * location client drops because of an error.
     */
    @Override
    public void onDisconnected() 
    {
        // Display the connection status
        Toast.makeText(this, "Disconnected. Please re-connect.",
                Toast.LENGTH_SHORT).show();
    }

    /*
     * Called by Location Services if the attempt to
     * Location Services fails.
     */
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) 
    {
        /*
         * Google Play services can resolve some errors it detects.
         * If the error has a resolution, try sending an Intent to
         * start a Google Play services activity that can resolve
         * error.
         */
        if (connectionResult.hasResolution()) {
            try 
            {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(
                        this,
                        CONNECTION_FAILURE_RESOLUTION_REQUEST);
                /*
                 * Thrown if Google Play services cancelled the original
                 * PendingIntent
                 */
            } 
            catch (IntentSender.SendIntentException e) 
            {
                // Log the error
                e.printStackTrace();
            }
        } 
        else 
        {
            /*
             * If no resolution is available, display a dialog to the
             * user with the error.
             */
            showErrorDialog(connectionResult.getErrorCode());
        }
    }

    private void showErrorDialog(int errorCode) 
    {
        new AlertDialog.Builder(this)
            .setMessage(String.valueOf(errorCode))
            .setPositiveButton(android.R.string.ok,
                new DialogInterface.OnClickListener() 
                {
                public void onClick(DialogInterface dialog, int id) 
                {
                    dialog.dismiss();
                }
                }).show();
    }

    // Define the callback method that receives location updates
    @Override
    public void onLocationChanged(Location location) 
    {
        // Report to the UI that the location was updated
        String msg = "Updated Location: " +
                Double.toString(location.getLatitude()) + "," +
                Double.toString(location.getLongitude());
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}

当我尝试加载此页面时#39;通过单击上一页中的按钮,它不会加载。我至少期待加载地图(Top Gear测试轨道)。

什么可以阻止地图加载? 我的方法是创造我正确的方法吗?

我几乎跟着: http://developer.android.com/training/location/retrieve-current.html http://developer.android.com/training/location/receive-location-updates.html (我对共享偏好的事情感到困扰)。

我想测试它我最好使用我的家乡位置lat / lang但是目前我无法显示地图?这是在我的HTC One上测试的,所以不应该是Google Play服务问题,因为加载这个问题的屏幕是静态的(放大/缩小除外)地图。

我很欣赏这是一个很大的'问题,我希望有经验的人提供反馈/创建一个位置感知的'应用

感谢。

1 个答案:

答案 0 :(得分:0)

您可以参考文章https://software.intel.com/en-us/articles/implementing-map-and-geofence-features-in-android-business-apps

  1. 添加Android Manifest权限:

    <uses-permission android:name=”android.permission.INTERNET"/>
    

  2. <meta-data
              android:name="com.google.android.gms.version"
              android:value="@integer/google_play_services_version" />
    
      <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
          android:value="copy your API Key here"/>
    
    1. 添加地图片段:

    2. …
      private static final LatLng CHANDLER = new LatLng(33.455,-112.0668);
      …
      private static final StoreLocation[] ALLRESTURANTLOCATIONS = new StoreLocation[] {
          new StoreLocation(new LatLng(33.455,-112.0668), new String("Phoenix, AZ")),
          new StoreLocation(new LatLng(33.5123,-111.9336), new String("SCOTTSDALE, AZ")),
          new StoreLocation(new LatLng(33.3333,-111.8335), new String("Chandler, AZ")),
          new StoreLocation(new LatLng(33.4296,-111.9436), new String("Tempe, AZ")),
          new StoreLocation(new LatLng(33.4152,-111.8315), new String("Mesa, AZ")),
          new StoreLocation(new LatLng(33.3525,-111.7896), new String("Gilbert, AZ"))
      };
      …    
        @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.geolocation_view);
      
          mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.storelocationmap)).getMap();
          mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(CHANDLER, ZOOM_LEVEL));
          Drawable iconDrawable = getResources().getDrawable(R.drawable.ic_launcher);
          Bitmap iconBmp = ((BitmapDrawable) iconDrawable).getBitmap();
          for(int ix = 0; ix < ALLRESTURANTLOCATIONS.length; ix++) {
              mMap.addMarker(new MarkerOptions()
                  .position(ALLRESTURANTLOCATIONS[ix].mLatLng)
                  .icon(BitmapDescriptorFactory.fromBitmap(iconBmp)));
          }
      

      然后添加LocationListener和位置更新回调。