-5

I want to show my current location using Google maps v2 from a fragment however the Google maps is not initializing on start up. When i run the application, it is nor crashing but the map is not showing my current location neither is it displaying anything. I have used this code on my activity and it is fully functional.

Below is my java code:

public class MapFragment extends Fragment implements LocationListener,GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,OnMapReadyCallback {
    SupportMapFragment mSupportMapFragment;
    MapView mMapView;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    private MarkerOptions markerOptions;
    protected GoogleApiClient mGoogleApiClient;
    private LatLng latLng;
    public GoogleMap mMap;
    private Marker marker;
    LocationRequest mLocationRequest;
    private GoogleMap googleMap;
    private TextView lastTrip, lastDeliveryText, lastDelivery, lastAmountText, lastAmount, kes,
            todayTotal, totalDeliveryText, totalDelivery, totalAmount, totalAmountText;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        buildGoogleApiClient();
        // inflat and return the layout
        View v = inflater.inflate(R.layout.map_fragment, container,
                false);

        mSupportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapwhere);
        if (mSupportMapFragment == null) {
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            mSupportMapFragment = SupportMapFragment.newInstance();
            fragmentTransaction.replace(R.id.mapwhere, mSupportMapFragment).commit();
        }

        if (mSupportMapFragment != null) {
            mSupportMapFragment.getMapAsync(this);
        }


        return v;
    }
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        Log.d("one","one");

        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        //mMap.getUiSettings().setZoomControlsEnabled(true);
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                Log.d("two","two");
                buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);

            }
        } else {
            Log.d("three","three");
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);

        }
    }
    protected synchronized void buildGoogleApiClient() {
        Log.d("four","four");
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .addApi(Places.GEO_DATA_API)
                .build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d("five","five");
        mLastLocation = location;

        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }
        //mMap.getUiSettings().setZoomControlsEnabled(true);

        final Double lat = location.getLatitude();
        final Double lng = location.getLongitude();
        Log.d("LATLANGz", lat + "|" + lng);
        latLng = new LatLng(lat, lng);
        markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Positionn");
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), 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;
        }
        mMap.setMyLocationEnabled(false);

        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.user_location));

        marker = mMap.addMarker(markerOptions);

        //move map camera_main
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("hey2","hey2");
//        mMapView.onResume();
        mSupportMapFragment.onResume();
    }

    @Override
    public void onPause() {

        super.onPause();
        Log.d("hey1","hey1");
        //  mMapView.onPause();
        mSupportMapFragment.onPause();
    }

   /* @Override
    public void onDestroy() {
        super.onDestroy();
        //  mMapView.onDestroy();
        mSupportMapFragment.onDestroy();
    }*/

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        //  mMapView.onLowMemory();
        mSupportMapFragment.onLowMemory();
    }

    @Override
    public void onDetach() {
        Log.d("detach", "detach");
        super.onDetach();
        mSupportMapFragment.onDetach();

    }


    @Override
    public void onConnected(@Nullable Bundle bundle) {
        Log.d("six","six");
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        if (mGoogleApiClient.isConnected()){
            Log.d("seven","six");
            if (ContextCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            }
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
G. Joe
  • 53
  • 2
  • 15

2 Answers2

0

First check your permissions and your google api key in your manifest

Your xml layout must be something like this without any thing else:

.   <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="com.isg_biz.isg_tracking.MainActivity" />

You have to implement OnMapReadyCallback, then your code should be something like this in onCreate() :

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

Do not to copy and past the same xml code literally you have to change (tools : .....) to same that exist in your xml

for documentation, java code & more Please read :

https://developers.google.com/maps/documentation/android-api/map-with-marker

Baraa Aljabban
  • 992
  • 13
  • 22
0

first of all Chaeck permission in manifest

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

then check method for current location

private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
    @Override
    public void onMyLocationChange(Location location) {
        LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
        marker = map.addMarker(new MarkerOptions().position(loc));
        if(map != null){
            map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
        }
    }
};

then use

mMap.setOnMyLocationChangeListener(myLocationChangeListener);

and be patience map take laoding time depend on you network speed

comment if any query

Vinesh Chauhan
  • 1,288
  • 11
  • 27