4

After running my project, it shows blank maps, I followed many methods but still shows blank now i am confused with the map api v2,my console does not shows all api version this is my console image it does not shows all api version

This is my java file

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(requestCode==1)
    {
        if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED)
        {
            if(ContextCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED)
            {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
            }
        }
    }

}



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // 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);
}


/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    locationManager=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
    locationListener=new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            LatLng myplace = new LatLng(location.getLatitude(),location.getLongitude());
            mMap.addMarker(new MarkerOptions().position(myplace).title("veraval").icon(BitmapDescriptorFactory.
                    defaultMarker(BitmapDescriptorFactory.HUE_RED)));
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myplace,20));

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };


        if (ContextCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        } else {
            Toast.makeText(MapsActivity.this,"hello",Toast.LENGTH_LONG).show();

            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

        }



}

This is my build.gradle file, I have added all the dependencies still it shows the blank map

android {
compileSdkVersion 27
defaultConfig {
    applicationId "com.example.user.mapexample"
    minSdkVersion 19
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        resValue "string", "google_maps_api_key", "Release_API_KEY"

    }
    debug{
        resValue "string", "google_maps_api_key", "DEBUG_API_KEY"
    } 
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:support-v4:27.1.1'
implementation 'com.android.support:support-media-compat:27.1.1'
implementation 'com.google.android.gms:play-services-maps:15.0.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:0.5'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

This is my logcat

07-26 12:14:12.046 7855-7855/? I/art: Late-enabling -Xcheck:jni
07-26 12:14:12.071 7855-7862/? I/art: Debugger is no longer active
07-26 12:14:12.071 7855-7862/? I/art: Starting a blocking GC Instrumentation
07-26 12:14:12.204 7855-7855/? D/LenovoAppIconTheme: 
ExtraResources;cleanCachedIcon;clear cache..
07-26 12:14:12.210 7855-7855/? W/System: ClassLoader referenced unknown path: 
/data/app/com.example.user.mapsexample-1/lib/arm
07-26 12:14:12.338 7855-7855/? I/zzbz: Making Creator dynamically
07-26 12:14:12.380 7855-7855/? I/DynamiteModule: Considering local module 
com.google.android.gms.maps_dynamite:0 and remote module 
com.google.android.gms.maps_dynamite:220
07-26 12:14:12.380 7855-7855/? I/DynamiteModule: Selected remote version of 
com.google.android.gms.maps_dynamite, version >= 220
07-26 12:14:12.404 7855-7855/? W/System: ClassLoader referenced unknown path: 
07-26 12:14:12.518 7855-7855/? I/Google Maps Android API: Google Play 
services client version: 12451000
07-26 12:14:12.540 7855-7855/? I/Google Maps Android API: Google Play 
services package version: 12874022
07-26 12:14:13.312 7855-7855/com.example.user.mapsexample E/art: The 
String#value field is not present on Android versions >= 6.0
07-26 12:14:13.690 7855-7901/com.example.user.mapsexample 
D/NetworkSecurityConfig: No Network Security Config specified, using platform 
default
07-26 12:14:13.709 7855-7901/com.example.user.mapsexample I/DpmTcmClient: 
RegisterTcmMonitor from: com.android.okhttp.TcmIdleTimerMonitor
07-26 12:14:13.930 7855-7936/com.example.user.mapsexample I/Adreno: QUALCOMM 
build                   : 5817cca, Ie9c95840c4
                                                                Build Date                       
: 03/26/17
                                                                OpenGL ES 
Shader Compiler Version: XE031.09.00.03
                                                                Local Branch                     
: 
                                                                Remote Branch                    
: refs/tags/AU_LINUX_ANDROID_LA.UM.5.5.R1.07.00.00.269.021
                                                                Remote Branch                    
: NONE
                                                                Reconstruct 
Branch               : NOTHING
07-26 12:14:13.956 7855-7936/com.example.user.mapsexample I/OpenGLRenderer: 
Initialized EGL, version 1.4
07-26 12:14:13.957 7855-7936/com.example.user.mapsexample D/OpenGLRenderer: 
Swap behavior 1
07-26 12:14:14.258 7855-7866/com.example.user.mapsexample W/art: Suspending 
all 
threads took: 18.013ms
07-26 12:14:14.287 7855-7866/com.example.user.mapsexample I/art: Background 
sticky concurrent mark sweep GC freed 7913(862KB) AllocSpace objects, 
20(1612KB) LOS objects, 0% free, 13MB/13MB, paused 20.215ms total 77.392ms
07-26 12:14:14.743 7855-7866/com.example.user.mapsexample I/art: Background 
sticky concurrent mark sweep GC freed 4729(195KB) AllocSpace objects, 4(2MB) 
LOS objects, 9% free, 25MB/28MB, paused 5.557ms total 19.833ms
07-26 12:14:16.187 7855-7934/com.example.user.mapsexample W/DynamiteModule: 
Local module descriptor class for com.google.android.gms.googlecertificates 
not found.
07-26 12:14:16.199 7855-7934/com.example.user.mapsexample I/DynamiteModule: 
Considering local module com.google.android.gms.googlecertificates:0 and 
remote module com.google.android.gms.googlecertificates:4
07-26 12:14:16.199 7855-7934/com.example.user.mapsexample I/DynamiteModule: 
Selected remote version of com.google.android.gms.googlecertificates, version 
>= 4

This is the output I am getting in my physical device

InsaneCat
  • 2,115
  • 5
  • 21
  • 40
aksishere
  • 53
  • 1
  • 7

1 Answers1

6

build.gradle

buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "google_maps_api_key", "Release_API_KEY"
        }
        debug {
//          KL MBP debug Key
            resValue "string", "google_maps_api_key", "DEBUG_API_KEY"
//          KL Old Machine debug Key
//            resValue "string", "google_maps_api_key", "DEBUG_API_KEY"
        }
    }

AndroidManifest.xml

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

<uses-library
    android:name="com.google.android.maps"
    android:required="true" />

Check my answer for more details on how to setup API key google_maps_api_key and add to build.gradle as release or debug.

Update 1

  • Easy way to setup Google Maps API key.

  • To get one, follow this link, follow the directions and press "Create" at the end:

    https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r={SHA-1}%3B{YOUR_APP_PACKAGE_NAME}

    • Ex:

      https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=08:F2:4F:C5:43:3E:4E:B7:30:71:0F:06:F1:9F:85:F5:E2:1D:B8:73%3Bcom.lelasoft.googlemapv2

Note: It may take up to 5 minutes for settings to take effect

Update 2

  • I created new MapActivity and it works with me after setup API key using Update 1 instruction and it take about 5 minutes to take effect

Update 3

  • Set Android emulator GeoLocation

enter image description here

Update 4

  • Ask user to enable GeoLocation on device.

build.gradle

dependencies {
     // Other dependences 
    implementation 'com.google.android.gms:play-services-location:15.0.1' // add location dependency.
    implementation 'com.google.android.gms:play-services-maps:15.0.1'
}

MapsActivity.java

@Override
public void onMapReady(GoogleMap googleMap) {
    this.googleMap = googleMap;
    buildGoogleApiClient();
    googleApiClient.connect();
}

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

@Override
public void onLocationChanged(Location location) {
    googleMap.clear();
    LatLng myplace = new LatLng(location.getLatitude(), location.getLongitude());

    // Add a marker in Sydney and move the camera
    googleMap.addMarker(new MarkerOptions().position(myplace).title("Marker in My Current Location"));
    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myplace,17));
}

/**
 * Enables the My Location layer if the fine mLocation permission has been granted.
 */
private void enableMyLocation() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
            && ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_ACCESS_FINE_LOCATION_PERMISSION);
    }else if (googleApiClient != null && locationRequest !=null){
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
        googleMap.setMyLocationEnabled(true);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    switch (requestCode) {
        case REQUEST_ACCESS_FINE_LOCATION_PERMISSION:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                enableMyLocation();
            }
            break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_ACCESS_FINE_LOCATION_PERMISSION){
        enableMyLocation();
    }
}


@Override
public void onResume() {
    super.onResume();
    if (googleApiClient !=null)
        createLocationRequest();
}


protected void createLocationRequest() {
    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(googleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(@NonNull LocationSettingsResult result) {
            final Status status = result.getStatus();
            final LocationSettingsStates state = result.getLocationSettingsStates();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    // All mLocation settings are satisfied. The client can initialize mLocation
                    // requests here.
                    enableMyLocation();
                    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(MapsActivity.this, REQUEST_ACCESS_FINE_LOCATION_PERMISSION);
                    } 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;
            }
        }
    });
}

Check complete Github Example.

Khaled Lela
  • 7,831
  • 6
  • 45
  • 73