qqrrrr
qqrrrr

Reputation: 585

onMapReady won't display map

I have two project with almost the same code but this one won't show map instead it will only toast what I put inside the

onMapReady

I do have a public class that extends FragmentActivity and implements OnMapReadyCallback

 private GoogleMap mMap;

Made my GoogleMap private because it works on my other project.

Also inside my onCreate is this followed by the onMapReady

SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

@Override
public void onMapReady(GoogleMap googleMap) {
    Toast.makeText(MapsActivity.this, "onMapReady", Toast.LENGTH_SHORT).show();
    mMap = googleMap;

    LatLng start = new LatLng(10.008154, 123.635460);
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(start, 9));
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    } else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }
}
protected synchronized void buildGoogleApiClient() {
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
    if (mGoogleApiClient != null) {
        mGoogleApiClient.connect();
    }
}


<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" />

It only shows like this It only shows like this instead of enter image description here

Please do not mind the markers.

Upvotes: 0

Views: 579

Answers (1)

Jay Dangar
Jay Dangar

Reputation: 3469

I have used fusedlocation Provider API to get current location of the User.

 public class activityPlot extends AppCompatActivity implements
            OnMapReadyCallback{

        private String TAG = activityPlot.class.getSimpleName();

        private GoogleMap mMap;
        private Boolean mLocationPermissionGranted = false;
        private FusedLocationProviderClient mFusedLocationProviderClient;
        private LatLng mDefaultLocation;
        private Location mLastKnownLocation;

        //  Request Code for Location Permission...
        private static final int LOCATION_PERMISSION_REQUEST_CODE = 438;

        @SuppressLint({"ClickableViewAccessibility", "ResourceType"})
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_plot);

            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
            if (mapFragment != null) {
                View mapView = mapFragment.getView();
                if (mapView != null &&
                        mapView.findViewById(1) != null) {
                    @SuppressLint("ResourceType") View locationButton = ((View) mapView.findViewById(1).getParent()).findViewById(2);
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
                            locationButton.getLayoutParams();
                    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
                    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
                    layoutParams.setMargins(0, 0, 30, 200);
                }
                mapFragment.getMapAsync(this);
            }

            mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        }

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

            updateLocationUI();
            getDeviceLocation();
        }

        private void getLocationPermission() {
            Log.i(TAG, "asking for permission");
            if (ContextCompat.checkSelfPermission(this.getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                mLocationPermissionGranted = true;
                updateLocationUI();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
            }
        }

        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
            mLocationPermissionGranted = false;
            switch (requestCode) {
                case LOCATION_PERMISSION_REQUEST_CODE: {
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        mLocationPermissionGranted = true;
                    }
                }
            }
            updateLocationUI();
        }

        private void updateLocationUI() {
            if (mMap == null) {
                return;
            }
            try {
                if (mLocationPermissionGranted) {
                    mMap.setMyLocationEnabled(true);
                    mMap.getUiSettings().setMyLocationButtonEnabled(true);
                } else {
                    mMap.setMyLocationEnabled(false);
                    mMap.getUiSettings().setMyLocationButtonEnabled(false);
                    mLastKnownLocation = null;
                    getLocationPermission();
                }
            } catch (SecurityException e) {
                Log.e("Exception: %s", e.getMessage());
            }
        }

        private void getDeviceLocation() {
            try {
                if (mLocationPermissionGranted) {
                    Task locationResult = mFusedLocationProviderClient.getLastLocation();
                    locationResult.addOnCompleteListener(this, task -> {
                        if (task.isSuccessful()) {
                            mLastKnownLocation = (Location) task.getResult();
                            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), 17));
                        } else {
                            Log.d(TAG, "Current location is null. Using defaults.");
                            Log.e(TAG, "Exception: %s", task.getException());
                            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, 17));
                            mMap.getUiSettings().setMyLocationButtonEnabled(false);
                        }
                    });
                }
            } catch (SecurityException e) {
                Log.e("Exception: %s", e.getMessage());
            }
        }
    }

My XML File looks like this:->

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    orientation="vertical"
    tools:context=".activityPlot">

 <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Manifest File ->

// Add Permissions and Meta-Data for key...
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="android.example.com.googlemap">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        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>
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />
    </application>

</manifest>

Add these dependencies in Gradle File ->

 //  Maps, Places and Location Libraries...
    implementation 'com.google.android.gms:play-services-maps:15.0.1'
    implementation 'com.google.android.gms:play-services-location:15.0.1'

Upvotes: 1

Related Questions