无法在Android地图中获取我当前的位置android并缩放到当前位置

时间:2015-12-06 18:09:38

标签: android google-maps geolocation cllocationmanager locationlistener

我正在创建一个位置应用程序我在第一步卡住了,我无法在地图上获取当前位置。我已经编写了代码,我不明白我做了什么错误。

我的代码如下所示:

public class MainActivity extends FragmentActivity implements LocationListener, GoogleMap.OnMarkerClickListener {

    GoogleMap mGoogleMap;

    List<LatLng> routePoints;
    String[] mPlaceType = null;
    String[] mPlaceTypeName = null;
    private ArrayList<LatLng> arrayPoints = null;
    private LocationRequest mLocationRequest;
    private static final long INTERVAL = 5000; //one second
    private static final long FASTEST_INTERVAL = 5000; // one second
    private static final float SMALLEST_DISPLACEMENT = 0.01F; //one tenth of a meter
    double mLatitude = 0, selectedLatitude = 0, sourceLatitude = 0, sourceLongitude = 0;
    double mLongitude = 0, selectedLongitude = 0;
    private boolean isPermissionRequest = false;
    private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 1;
    private ArrayList<LatLng> points; //added
    LocationManager locationManager;
    String provider;

    Polyline line; //added

    String url;

    HashMap<String, String> mMarkerPlaceLink = new HashMap<String, String>();
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;


    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setSmallestDisplacement(SMALLEST_DISPLACEMENT); //added
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        points = new ArrayList<LatLng>(); //added

        createLocationRequest();


        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
        if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();
        } else { // Google Play Services are available

            // Getting reference to the SupportMapFragment
            SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting Google Map
            mGoogleMap = fragment.getMap();

        }

        if (!isAllPermissionAvailable(this) && isGreaterThanLollipop()) {
            isPermissionRequest = true;
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
            Log.v("My Application", "RequestPermissions Inside");
            // return;
        }
 client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

 @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_READ_PHONE_STATE) {
            Log.v("My Application", "onRequestPermissionsResult");
            isPermissionRequest = false;
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                // Enabling MyLocation in Google Map
                mGoogleMap.setMyLocationEnabled(true);
                mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
                mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
                mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
                mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLatitude, mLongitude), 14.0f));


                // Getting LocationManager object from System Service LOCATION_SERVICE
                locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

                // Creating a criteria object to retrieve provider
                Criteria criteria = new Criteria();

                // Getting the name of the best provider
                provider = locationManager.getBestProvider(criteria, true);
                Location location = locationManager.getLastKnownLocation(provider);

                if (location != null) {
                    onLocationChanged(location);
                }

                locationManager.requestLocationUpdates(provider, 20000, 0, this);

            }

        }
    }


    @Override
    public void onLocationChanged(Location location) {
        mLatitude = location.getLatitude();
        mLongitude = location.getLongitude();
        LatLng latLng = new LatLng(mLatitude, mLongitude);

        sourceLatitude = mLatitude;
        sourceLongitude = mLongitude;

        Log.d("iFocus", "The value of sourceLatitude and sourceLongitude is " + sourceLatitude + " " + sourceLongitude);

        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLatitude, mLongitude), 14.0f));
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

    }

我的清单文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="tracker.osm.com.osmtracker">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">


        <permission
            android:name="tracker.osm.com.osmtracker.permission.MAPS_RECEIVE"
            android:protectionLevel="signature" />

        <uses-permission android:name="tracker.osm.com.osmtracker.permission.MAPS_RECEIVE" />
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

        <uses-feature
            android:glEsVersion="0x00020000"
            android:required="true" />


        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>




            <meta-data
                android:name="com.google.android.gms.version"
                android:value="@integer/google_play_services_version" />


        </activity>
        <!-- ATTENTION: This was auto-generated to add Google Play services to your project for
             App Indexing.  See https://g.co/AppIndexing/AndroidStudio for more information. -->

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyCd91rJroX1GkHOEg5_SnEq5j23Zwl707M" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    </application>

</manifest>

任何人都可以让我知道我的错误,我需要做些什么改变来克服我的问题。欢迎提出所有建议。

0 个答案:

没有答案