0

Google map is not Displaying in the API level 23,24,25 but it is shown kitkat.Why is that Happening?

NearMe

public class NearMe extends Fragment {
    MapView mMapView;
    private GoogleMap googleMap;
    GpsLocation gpsLocation;
    double longitude, latitude;
    private ProgressDialog pDialog;
    ArrayList<MySchool> al_school = new ArrayList<MySchool>();
    ArrayList<MyCollege> al_college = new ArrayList<MyCollege>();
    ArrayList<MyUniversity> al_university = new ArrayList<MyUniversity>();

    private static final String TAG = NearMe.class.getSimpleName();

    private static final String urlSchool = "http://www.myeducationhunt.com/api/v1/schools";
    private static final String urlCollege = "http://www.myeducationhunt.com/api/v1/colleges";
    private static final String urlUniversity = "http://www.myeducationhunt.com/api/v1/universities";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        final View v = inflater.inflate(R.layout.fragment_near_me, container, false);

        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);


        if (isConnected()) {
            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                Toast.makeText(getContext(), "GPS is Enabled in your device", Toast.LENGTH_SHORT).show();

                mMapView = (MapView) v.findViewById(R.id.mapView);
                mMapView.onCreate(savedInstanceState);

                mMapView.onResume();

                try {
                    MapsInitializer.initialize(getActivity().getApplicationContext());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                gpsLocation = new GpsLocation(getContext());


                if (gpsLocation.canGetLocation()) {
                    longitude = gpsLocation.getLongitude();
                    latitude = gpsLocation.getLatitude();

                    Toast.makeText(getContext(), "latitude:" + latitude + "Longitude:" + longitude, Toast.LENGTH_LONG).show();
                }


                pDialog = new ProgressDialog(getContext());
                pDialog.setMessage("Loading…");
                pDialog.show();


                mMapView.getMapAsync(new OnMapReadyCallback() {
                    @Override
                    public void onMapReady(GoogleMap mMap) {
                        googleMap = mMap;

                        LatLng schoollatlng = new LatLng(latitude, longitude);
                        googleMap.addMarker(new MarkerOptions().position(schoollatlng).title("MyLocation"));
                        CameraPosition cameraPosition = new CameraPosition.Builder().target(schoollatlng).zoom(11).build();
                        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

                        drawSchoolMarker();
                        drawCollegeMarker();
                        drawUniversityMarker();
                    }
                });
            }
            else{
                showGPSDisabledAlertToUser();
            }
        } else {

            Toast.makeText(getContext(), "Please check your internet connection", Toast.LENGTH_LONG).show();
        }

        return v;
    }

    public boolean isConnected() {
        ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Activity.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected())
            return true;
        else
            return false;
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    private void drawSchoolMarker() {

        JsonArrayRequest schoolRequest = new JsonArrayRequest(urlSchool,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                MySchool school = new MySchool();

                                school.setId("" + obj.getInt("id"));
                                school.setName("" + obj.getString("name"));
                                school.setLatitude(Double.parseDouble("" + obj.getDouble("latitude")));
                                school.setLongitude(Double.parseDouble("" + obj.getDouble("longitude")));


                                al_school.add(school);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        //iterate from arraylist
                        for (MySchool school : al_school) {

                            View marker = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker, null);
                            TextView numTxt = (TextView) marker.findViewById(R.id.num_txt);
                            numTxt.setText(school.getName());
                            LatLng latlng = new LatLng(school.getLatitude(), school.getLongitude());
                            googleMap.addMarker(new MarkerOptions().position(latlng).icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(getContext(), marker))).title(school.getName()));
                        }


                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();
            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(schoolRequest);
    }

    private void drawCollegeMarker() {
        JsonArrayRequest collegeRequest = new JsonArrayRequest(urlCollege,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                MyCollege college = new MyCollege();

                                college.setId("" + obj.getInt("id"));
                                college.setName("" + obj.getString("name"));
                                college.setLatitude(Double.parseDouble("" + obj.getDouble("latitude")));
                                college.setLongitude(Double.parseDouble("" + obj.getDouble("longitude")));


                                al_college.add(college);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        //iterate from arraylist
                        for (MyCollege college : al_college) {

                            View marker = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_college, null);
                            TextView numTxt = (TextView) marker.findViewById(R.id.txt_college);
                            numTxt.setText(college.getName());
                            LatLng latlng = new LatLng(college.getLatitude(), college.getLongitude());
                            googleMap.addMarker(new MarkerOptions().position(latlng).icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(getContext(), marker))).title(college.getName()));
                        }


                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();
            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(collegeRequest);
    }

    private void drawUniversityMarker() {
        JsonArrayRequest uniRequest = new JsonArrayRequest(urlUniversity,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                MyUniversity university = new MyUniversity();

                                university.setId("" + obj.getInt("id"));
                                university.setName("" + obj.getString("name"));
                                university.setLatitude(Double.parseDouble("" + obj.getDouble("latitude")));
                                university.setLongitude(Double.parseDouble("" + obj.getDouble("longitude")));


                                al_university.add(university);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        //iterate from arraylist
                        for (MyUniversity university : al_university) {

                            View marker = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_university, null);
                            TextView numTxt = (TextView) marker.findViewById(R.id.txt_university);
                            numTxt.setText(university.getName());
                            LatLng latlng = new LatLng(university.getLatitude(), university.getLongitude());
                            googleMap.addMarker(new MarkerOptions().position(latlng).icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(getContext(), marker))).title(university.getName()));
                        }


                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();
            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(uniRequest);
    }

    public static Bitmap createDrawableFromView(Context context, View view) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
        view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
        view.buildDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);

        return bitmap;
    }

    private void showGPSDisabledAlertToUser(){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
        alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
                .setCancelable(false)
                .setPositiveButton("Goto Settings Page To Enable GPS",
                        new DialogInterface.OnClickListener(){
                            public void onClick(DialogInterface dialog, int id){
                                Intent callGPSSettingIntent = new Intent(
                                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivity(callGPSSettingIntent);
                            }
                        });
        alertDialogBuilder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener(){
                    public void onClick(DialogInterface dialog, int id){
                        dialog.cancel();
                    }
                });
        AlertDialog alert = alertDialogBuilder.create();
        alert.show();
    }
}

GpsLocation class

public class GpsLocation extends Service implements LocationListener {
    private final Context mContext;
    // flag for GPS status
    boolean isGPSEnabled = false;
    // flag for network status
    boolean isNetworkEnabled = false;
    // flag for GPS status
    boolean canGetLocation = false;
    Location location; // location
    double latitude; // latitude
    double longitude; // longitude
    double speed, direction;
    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GpsLocation(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);
            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        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
                            //    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 TODO;
                        }
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            Log.d("Getting location", "Location found");
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     */
    public void stopUsingGPS() {
        if (locationManager != null) {
            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
                //    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;
            }
            locationManager.removeUpdates(GpsLocation.this);
        }
    }

    /**
     * Function to get latitude
     */
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }
        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     */
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }
        // return longitude
        return longitude;
    }

    public double getSpeed() {
        return speed;
    }

    public double getDirection() {
        return direction;
    }

    /**
     * Function to check GPS/wifi enabled
     *
     * @return boolean
     */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will launch Settings Options
     */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");
        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });
        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            speed = location.getSpeed();
            direction = location.getBearing();
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

is it showing ocean location.??

enter image description here

What is the exact issue i am not able to know and how can this be resolved?

seon
  • 1,050
  • 2
  • 13
  • 27

1 Answers1

2
  • Your coordinates point to sea(check the values load them in browser and see where it points)? If yes the map might be opening in the ocean check your zoom level(zoom out a lot and see any change is there )
  • If not there is something wrong with your API Key double check that as well.
  • Further more go through Request runtime permissions If you want an example check this > https://stackoverflow.com/a/34582595/5188159
Community
  • 1
  • 1
Charuක
  • 12,953
  • 5
  • 50
  • 88