0

I am developing an app, I created google map api but it doesn't shows map in application.Following is the code which i'm using.When i open the app map unable to show the current location.I want to show the current location of user.How do i do this?

java

public class Maps_Activity extends FragmentActivity implements
        OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        GoogleMap.OnMarkerDragListener,
        GoogleMap.OnMapLongClickListener,
        View.OnClickListener {

    //Our Map
    private GoogleMap mMap;
    public static final int REQUEST_ID_ACCESS_COURSE_FINE_LOCATION = 100;

    //To store longitude and latitude from map
    private double longitude;
    private double latitude;
    String caddress;

    //Buttons
    private ImageButton buttonSave;
    private ImageButton buttonCurrent;
    private ImageButton buttonView;

    private Button btnProceed, btnskip, btnClocation;

    String strAdd;
    TextView tvmap,textview;

    private boolean loggedIn = false;
    public static String email;


    private ProgressDialog myProgress;

    //Google ApiClient
    private GoogleApiClient googleApiClient;


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

        tvmap=(TextView)findViewById(R.id.tv_map);
        textview=(TextView)findViewById(R.id.textView_euser);

        //progress bar
        myProgress = new ProgressDialog(this);
        myProgress.setTitle("Map Loading ...");
        myProgress.setMessage("Please wait...");
        myProgress.setCancelable(true);
        // Display Progress Bar.
        myProgress.show();

        // 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);

        //Initializing googleapi client
        googleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        //googleapi gps

    /*    googleApiClient = new GoogleApiClient
                .Builder(this)
                .enableAutoManage(this, 34992, this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
         locationChecker(googleApiClient, MapsActivity.this);   */

        //Initializing views and adding onclick listeners
        btnProceed=(Button)findViewById(R.id.button_proceed);
        btnskip=(Button)findViewById(R.id.button_skip);
        //    btnClocation=(Button)findViewById(R.id.button_clocation);

        btnProceed.setOnClickListener(this);
        btnskip.setOnClickListener(this);
        //    btnClocation.setOnClickListener(this);

        SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
        loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
        email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Not Available");
        textview.setText(email);

    }

    @Override
    protected void onResume() {

        LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        boolean enabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        if(!enabled) {
            showDialogGPS();
        }
        super.onResume();
    }

    private void showDialogGPS() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);
        builder.setTitle("Enable GPS");
        builder.setMessage("Please enable GPS");
        builder.setInverseBackgroundForced(true);
        builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                startActivity(
                        new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                getCurrentLocation();
                moveMap();
            }
        });
        builder.setNegativeButton("Ignore", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    }


    @Override
    public void onClick(View v) {
        if(v == btnProceed){
        //    getCurrentLocation();
        //    moveMap();
            if (loggedIn) {
                //We will start the Profile Activity

                submitForm();
                Intent i=new Intent(Maps_Activity.this,Search_ActivityND.class);
                startActivity(i);
            }

        }
        else if(v == btnskip){

            btnclick_skip();
        }
    /*   else if(v == btnClocation){

            getCurrentLocation();
            moveMap();
        }*/
    }

    //dalete alert
    private void btnclick_skip(){

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("Are you fine this Location?");
        alertDialogBuilder.setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {

                        //   new JSONParserD().execute();
                        //Starting login activity
                        Intent intent = new Intent(Maps_Activity.this, Search_ActivityND.class);
                        startActivity(intent);
                        //    if (loggedIn) {
                        //        Intent intent = new Intent(MapsActivity.this, Home.class);
                        //        startActivity(intent);
                        //    }

                    }
                });

        alertDialogBuilder.setNegativeButton("No",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {

                    }
                });

        //Showing the alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }


    //saving to database
    private void submitForm() {

        caddress = tvmap.getText().toString();
        email = textview.getText().toString();
        //  Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
        new MapAsync(this).execute(caddress,email);
    }

    @Override
    protected void onStart() {
        googleApiClient.connect();
        super.onStart();
    }

    @Override
    protected void onStop() {
        googleApiClient.disconnect();
        super.onStop();
    }

    //Getting current location
    private void getCurrentLocation() {
        mMap.clear();
        //Creating a location object
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        if (location != null) {
            //Getting longitude and latitude
            longitude = location.getLongitude();
            latitude = location.getLatitude();

            //    tvmap.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());

            strAdd = getCompleteAddressString(latitude, longitude);
            tvmap.setText("Current Address : " + strAdd);

            //moving the map to location
            moveMap();
        }
    }

    //Function to move the map
    private void moveMap() {
        //String to display current latitude and longitude
        String msg = latitude + ", "+longitude;

        //Creating a LatLng Object to store Coordinates
        LatLng latLng = new LatLng(latitude, longitude);

        //Adding marker to map
        mMap.addMarker(new MarkerOptions()
                .position(latLng) //setting position
                .draggable(true) //Making the marker draggable
                .title("Current Location")); //Adding a title

        //Moving the camera
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        //Animating the camera
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15));

        //Displaying current coordinates in toast
        //    Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

        mMap = googleMap;
        LatLng latLng = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.setOnMarkerDragListener(this);
        mMap.setOnMapLongClickListener(this);

    }

    @Override
    public void onConnected(Bundle bundle) {
        getCurrentLocation();
        myProgress.dismiss();
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    @Override
    public void onMapLongClick(LatLng latLng) {
        //Clearing all the markers
        mMap.clear();

        //Adding a new marker to the current pressed position
        mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .draggable(true));
    }

    @Override
    public void onMarkerDragStart(Marker marker) {

    }

    @Override
    public void onMarkerDrag(Marker marker) {

    }

    @Override
    public void onMarkerDragEnd(Marker marker) {
        //Getting the coordinates
        latitude = marker.getPosition().latitude;
        longitude = marker.getPosition().longitude;

        //Moving the map
        moveMap();
    }

    private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
        String strAdd = "";
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        try {
            List<Address> addresses = geocoder
                    .getFromLocation(LATITUDE, LONGITUDE, 1);
            if (addresses != null) {
                android.location.Address returnedAddress = addresses.get(0);
                StringBuilder strReturnedAddress = new StringBuilder("");

                for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
                    strReturnedAddress
                            .append(returnedAddress.getAddressLine(i)).append(
                            "\n");
                }
                strAdd = strReturnedAddress.toString();
                //   Log.w("My Current loction address",
                //           "" + strReturnedAddress.toString());
            } else {
                // Log.w("My Current loction address", "No Address returned!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            //  Log.w("My Current loction address", "Canont get Address!");
        }
        return strAdd;
    }
}

manifest

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

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

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <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:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="api"/>

        <activity
            android:name=".Splash_activity"
            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>
        </activity>

        <activity android:name=".Index_Activity"
            android:label="Login_Activity">
        </activity>

        <activity android:name=".Search_ActivityND"
                  android:label="Search Cab">
        </activity>

        <activity android:name=".Maps_Activity"
            android:label="Map">
        </activity>

    </application>

</manifest>  

xml

<FrameLayout 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"
    tools:context=".Maps_Activity">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="net.simplifiedcoding.mymapapp.MapsActivity" />

    <include layout="@layout/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></include>

    <!--
    <SearchView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/searchView"
        android:background="#ffffff"
        android:orientation="horizontal"
        android:layout_gravity="left|top" />  -->

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:textColor="#000000"
        android:background="#ffffff"
        android:orientation="horizontal"
        android:hint="Your PickUp Address"
        android:id="@+id/tv_map"
        android:layout_marginTop="60dp"
        android:layout_gravity="center_horizontal|top" />


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:orientation="horizontal"
        android:layout_gravity="right|bottom"
        android:weightSum="1">


        <Button
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="Skip"
            android:layout_marginLeft="10dp"
            android:id="@+id/button_skip" />

        <Button
            android:layout_width="139dp"
            android:layout_height="wrap_content"
            android:text="Procced"
            android:layout_marginRight="20dp"
            android:id="@+id/button_proceed" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="email"
            android:id="@+id/textView_euser" />

    </LinearLayout>

</FrameLayout>
Jitesh Prajapati
  • 2,533
  • 4
  • 29
  • 51
rohiH
  • 99
  • 3
  • 14
  • Is it showing gray screen instead of Map? – Doctor Who Sep 07 '16 at 09:19
  • blue blank screen shown by map – rohiH Sep 07 '16 at 09:22
  • You should go to the open area sometime it doesn't work when you are inside a house – Doctor Who Sep 07 '16 at 09:23
  • https://www.simplifiedcoding.net/android-google-maps-tutorial-google-maps-android-api/ ,I refer this code – rohiH Sep 07 '16 at 09:24
  • sometimes it shows accurate location but sometimes unable to show , and when i open the app sometimes it shows only map but not shows current location. – rohiH Sep 07 '16 at 09:26
  • In logcat shows this message "V/GoogleSignatureVerifier: com.google.android.gms signature not valid." – rohiH Sep 07 '16 at 09:27
  • Ok, I think you need to get the user location outside this activity and then use that `LatLng` value to open map on `onMapReady(GoogleMap googleMap)` callback – Sanoop Surendran Sep 07 '16 at 09:27
  • how do i do this? – rohiH Sep 07 '16 at 09:28
  • Only add this line after latitude and longitude is obtained. For that make `SupportMapFragment mapFragment` global and call `mapFragment.getMapAsync(this);` only after location is obtained.. Which i can figure where exactly in your code you are getting the latitude and longitude.. If furthur help needed i will post it as an answer – Sanoop Surendran Sep 07 '16 at 09:32

2 Answers2

1

You are getting blue screen because you are not getting the current location (Latitude and Longitude) . So the default value is taken as 0.0

Since you are using SupportMapFragment , Create a global object and on onCreate() initialize the mapFragment

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

do not call the

mapFragment.getMapAsync(this);

until you haven't obtained lat and lng

For that some changes are needed in your code, Firstly on onResume()

if(!enabled) {
    showDialogGPS();
} else {
   mapFragment.getMapAsync(this);
}

Secondly, on getCurrentLocation()

if (location != null) {
   //Getting longitude and latitude
   longitude = location.getLongitude();
   latitude = location.getLatitude();

   // tvmap.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());

   strAdd = getCompleteAddressString(latitude, longitude);
   tvmap.setText("Current Address : " + strAdd);

   mapFragment.getMapAsync(this);
}

and most importantly merge the contents on moveMap() with that of with onMapReady(GoogleMap googleMap) callback.

    mMap = googleMap;

    UiSettings uiSettings = mMap.getUiSettings();
    uiSettings.setCompassEnabled(true);
    // uiSettings.setZoomGesturesEnabled(true);
    uiSettings.setRotateGesturesEnabled(true);

    LatLng latLng = new LatLng(latitude, longitude);

   // other expressions for your interest

    mMap.addMarker(new MarkerOptions().position(latLng).title(title));
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));

Now you wont be needing the moveMap(), Since all the similar expressions are taken care by the onMapReady callback

EDIT

use these two dependency

compile 'com.google.android.gms:play-services-maps:9.2.1'
compile 'com.google.android.gms:play-services-location:9.2.1'

instead of

compile 'com.google.android.gms:play-services:9.0.2'

Hope this will fix the issues

Community
  • 1
  • 1
Sanoop Surendran
  • 3,484
  • 4
  • 28
  • 49
  • i tried above code but again map unable to show current location. – rohiH Sep 07 '16 at 10:29
  • ok. and logcat shows this message "V/GoogleSignatureVerifier: com.google.android.gms signature not valid." – rohiH Sep 07 '16 at 10:36
  • compile 'com.google.android.gms:play-services:9.0.2' this version i used – rohiH Sep 07 '16 at 10:37
  • @rohiH Please check my **EDIT** – Sanoop Surendran Sep 07 '16 at 10:41
  • According to [this](http://stackoverflow.com/a/37379789/5733111) and [this](http://stackoverflow.com/a/37407302/5733111), This is a bug on Android, So the solution is to downGrade the dependency So use `8.4.0' ie `com.google.android.gms:play-services-maps:8.4.0` and `'com.google.android.gms:play-services-location:8.4.0'` – Sanoop Surendran Sep 07 '16 at 10:46
0

I think can be two things

Your coordinates are 0,0 and the map is opening in the ocean

Something wrong with your API Key In the first case try zoom out a lot of times and try to see some continent.

In the second try to read the documentation or/and try this link

I hope this helps.

refer this link too

Normally blue screen means your Google API key didn't work.

Community
  • 1
  • 1
Doctor Who
  • 747
  • 1
  • 5
  • 28