MapView未加载

时间:2018-01-26 17:10:10

标签: android api maps android-mapview

我试图通过谷歌地方API显示附近的健身房,但问题     是地图没有加载你能告诉我问题在哪里吗?这是我的MapActivity.java,我使用特定的数据解析器只显示用户当前位置附近的健身房。

        package com.apkglobal.gymtrainer;
        import android.Manifest;
        import android.content.pm.PackageManager;
        import android.location.Location;
        import android.os.Build;
        import android.os.Bundle;
        import android.support.v4.app.ActivityCompat;
        import android.support.v4.app.FragmentActivity;
        import android.support.v4.content.ContextCompat;
        import android.view.View;
        import android.widget.Button;
        import android.widget.Toast;

        import com.google.android.gms.common.ConnectionResult;
        import com.google.android.gms.common.GoogleApiAvailability;
        import com.google.android.gms.common.api.GoogleApiClient;
        import com.google.android.gms.location.LocationListener;
        import com.google.android.gms.location.LocationRequest;
        import com.google.android.gms.location.LocationServices;
        import com.google.android.gms.maps.CameraUpdateFactory;
        import com.google.android.gms.maps.GoogleMap;
        import com.google.android.gms.maps.OnMapReadyCallback;
        import com.google.android.gms.maps.SupportMapFragment;
        import com.google.android.gms.maps.model.BitmapDescriptorFactory;
        import com.google.android.gms.maps.model.LatLng;
        import com.google.android.gms.maps.model.Marker;
        import com.google.android.gms.maps.model.MarkerOptions;

        public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
                GoogleApiClient.ConnectionCallbacks,
                GoogleApiClient.OnConnectionFailedListener,
                LocationListener {

            public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
            double latitude;
            double longitude;
            GoogleApiClient mGoogleApiClient;
            Location mLastLocation;
            Marker mCurrLocationMarker;
            LocationRequest mLocationRequest;
            private GoogleMap mMap;
            private int PROXIMITY_RADIUS = 10000;


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


                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    checkLocationPermission();
                }

                //Check if Google Play Services Available or not
                if (!CheckGooglePlayServices()) {
                    finish();
                } else {

                }

                // Obtain the SupportMapFragment and get notified when the map is ready to be used.
                SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                        .findFragmentById(R.id.map);
                mapFragment.getMapAsync(this);
            }

            private boolean CheckGooglePlayServices() {
                GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
                int result = googleAPI.isGooglePlayServicesAvailable(this);
                if (result != ConnectionResult.SUCCESS) {
                    if (googleAPI.isUserResolvableError(result)) {
                        googleAPI.getErrorDialog(this, result,
                                0).show();
                    }
                    return false;
                }
                return true;
            }

            @Override
            public void onMapReady(GoogleMap googleMap) {
                mMap = googleMap;
                mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {
                        buildGoogleApiClient();
                        mMap.setMyLocationEnabled(true);
                    }
                } else {
                    buildGoogleApiClient();
                    mMap.setMyLocationEnabled(true);
                }

                Button btnGyms = (Button) findViewById(R.id.btnGyms);
                btnGyms.setOnClickListener(new View.OnClickListener() {
                    String search = "gym";
                    @Override
                    public void onClick(View v) {
                        mMap.clear();
                        String url = getUrl(latitude, longitude, search);
                        Object[] DataTransfer = new Object[2];
                        DataTransfer[0] = mMap;
                        DataTransfer[1] = url;
                        GetNearbyGymsData getNearbyGymsData = new GetNearbyGymsData();
                        getNearbyGymsData.execute(DataTransfer);
                        Toast.makeText(MapsActivity.this, "These are your Nearby Gyms! ", Toast.LENGTH_LONG).show();
                    }
                });
            }

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

            @Override
            public void onConnected(Bundle bundle) {
                mLocationRequest = new LocationRequest();
                mLocationRequest.setInterval(1000);
                mLocationRequest.setFastestInterval(1000);
                mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {
                    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
                }
            }

            private String getUrl(double latitude, double longitude, String nearbyPlace) {

                StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
                googlePlacesUrl.append("location=" + latitude + "," + longitude);
                googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
                googlePlacesUrl.append("&type=" + nearbyPlace);
                googlePlacesUrl.append("&sensor=true");
                googlePlacesUrl.append("&key=" + "AIzaSyBdqKOYwGuY8jFH9ImVH7nmM_k868Wodrg");
                return (googlePlacesUrl.toString());
            }

            @Override
            public void onConnectionSuspended(int i) {

            }

            @Override
            public void onLocationChanged(Location location) {

                mLastLocation = location;
                if (mCurrLocationMarker != null) {
                    mCurrLocationMarker.remove();
                }

                //Place current location marker
                latitude = location.getLatitude();
                longitude = location.getLongitude();
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(latLng);
                markerOptions.title("You are Here!");
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
                mCurrLocationMarker = mMap.addMarker(markerOptions);

                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
                Toast.makeText(MapsActivity.this, "Your Current Location", Toast.LENGTH_LONG).show();

                if (mGoogleApiClient != null) {
                    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
                }
            }

            @Override
            public void onConnectionFailed(ConnectionResult connectionResult) {

            }

            public boolean checkLocationPermission() {
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)) {
                        ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                MY_PERMISSIONS_REQUEST_LOCATION);
                    } else {
                        ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                MY_PERMISSIONS_REQUEST_LOCATION);
                    }
                    return false;
                } else {
                    return true;
                }
            }

            @Override
            public void onRequestPermissionsResult(int requestCode,
                                                   String permissions[], int[] grantResults) {
                switch (requestCode) {
                    case MY_PERMISSIONS_REQUEST_LOCATION: {
                        if (grantResults.length > 0
                                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                            if (ContextCompat.checkSelfPermission(this,
                                    Manifest.permission.ACCESS_FINE_LOCATION)
                                    == PackageManager.PERMISSION_GRANTED) {

                                if (mGoogleApiClient == null) {
                                    buildGoogleApiClient();
                                }
                                mMap.setMyLocationEnabled(true);
                            }

                        } else {
                            Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                        }
                        return;
                    }
                }
            }

        }

这是我在MapView的XML文件,我试图加载MapView。它显示在活动中但Map未加载。你能告诉我这是什么问题吗?

        FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#2F4159">


            <fragment
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/map"
                android:name="com.google.android.gms.maps.SupportMapFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="10dp"/>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom"
                android:gravity="center">

                <Button
                    android:id="@+id/btnGyms"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Gyms"
                    android:background="#009A9A"
                    android:textColor="#FFFFFF"
                    android:layout_gravity="bottom"/>

            </RelativeLayout>

        </FrameLayout>

这是我的清单文件,我使用了精确位置的权限。我们需要添加任何其他权限吗?

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

            <!--
                 The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
                 Google Maps Android API v2, but you must specify either coarse or fine
                 location permissions for the 'MyLocation' functionality. 
            -->
            <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
            <uses-permission android:name="android.permission.INTERNET"/>

            <application
                android:name="android.support.multidex.MultiDexApplication"
                android:allowBackup="true"
                android:icon="@mipmap/ic_launcher"
                android:label="@string/app_name"
                android:supportsRtl="true"
                android:theme="@style/AppTheme">
                <activity android:name=".MainActivity">
                    <intent-filter>
                        <action android:name="android.intent.action.MAIN" />

                        <category android:name="android.intent.category.LAUNCHER" />
                    </intent-filter>
                </activity>
                <activity android:name=".Exercises" />
                <activity android:name=".Diet" />
                <activity android:name=".Information" />
                <activity android:name=".GymStories" />
                <activity android:name=".Faq" />
                <activity android:name=".About" />
                <activity android:name=".stories.Sean" />
                <activity android:name=".stories.Silvester" />
                <activity android:name=".stories.Arnold" />
                <activity android:name=".stories.Vijendra" />
                <activity android:name=".stories.Bruce" />
                <activity android:name=".stories.Jackie" />
                <activity android:name=".stories.MikeTyson" />
                <!--
                     The API key for Google Maps-based APIs is defined as a string resource.
                     (See the file "res/values/google_maps_api.xml").
                     Note that the API key is linked to the encryption key used to sign the APK.
                     You need a different API key for each encryption key, including the release key that is used to
                     sign the APK for publishing.
                     You can define the keys for the debug and release targets in src/debug/ and src/release/. 
                -->
                <meta-data
                    android:name="com.google.android.geo.API_KEY"
                    android:value="@string/google_maps_key" />

                <activity
                    android:name=".MapsActivity"
                    android:label="@string/title_activity_maps"></activity>
            </application>

        </manifest>

0 个答案:

没有答案