2

MapFragment Image

I want to show map view in tab layout with viewpager. As you can see above the image. i am getting my latitude and longitude but its not showing me map and marker on my location. Here is my Code of this fragment class

public class MapFragment extends Fragment implements OnMapReadyCallback,        
GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    com.google.android.gms.location.LocationListener {


private GoogleMap mMap;
private MapView mapView;

private static final int MY_PERMISSION_REQUEST_CODE = 0;
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 1;

private LocationRequest mlocationRequest;
private GoogleApiClient mgoogleApiClient;
private Location mlastlocation;

private static int UPDATE_INTERVAL = 1000;
private static int FASTEST_INTERVAL = 3000;
private static int DISPLACEMENT = 10;

DatabaseReference ref;
GeoFire geofire;
Marker myCurrentMarker;

public MapFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view;

    // Inflate the layout for this fragment
    view = inflater.inflate(R.layout.fragment_map, container, false);

    mapView = (MapView) view.findViewById(R.id.mapView);
    mapView.onCreate(savedInstanceState);
    ref = FirebaseDatabase.getInstance().getReference("MyLocation");
    geofire = new GeoFire(ref);

    setUpLocation();

    return view;
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] 
permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSION_REQUEST_CODE:
            if (grantResults.length > 0 && grantResults[0] == 
PackageManager.PERMISSION_GRANTED) {
                if (checkPlaySercives()) {
                    buildGoogleApiClient();
                    creatLocationRequest();
                    displayLocation();
                }
            }
            break;
    }
}

private void setUpLocation() {
    if (ActivityCompat.checkSelfPermission(getActivity(), 
android.Manifest.permission.ACCESS_COARSE_LOCATION) != 
PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(getActivity(), 
android.Manifest.permission.ACCESS_FINE_LOCATION) != 
PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(getActivity(), new String[]{
                android.Manifest.permission.ACCESS_COARSE_LOCATION,
                android.Manifest.permission.ACCESS_FINE_LOCATION
        }, MY_PERMISSION_REQUEST_CODE);
    } else {
        if (checkPlaySercives()) {
            buildGoogleApiClient();
            creatLocationRequest();
            displayLocation();
        }
    }
}

private void displayLocation() {
    if (ActivityCompat.checkSelfPermission(getActivity(), 
android.Manifest.permission.ACCESS_COARSE_LOCATION) != 
PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(getActivity(), 
android.Manifest.permission.ACCESS_FINE_LOCATION) != 
PackageManager.PERMISSION_GRANTED) {
        return;
    }
    mlastlocation = 
LocationServices.FusedLocationApi.getLastLocation(mgoogleApiClient);
    if (mlastlocation != null) {
        final double latitude = mlastlocation.getLatitude();
        final double longitute = mlastlocation.getLongitude();

        final LatLng latLng = new LatLng(latitude, longitute);
        geofire.setLocation("You", new GeoLocation(latitude, longitute),
                new GeoFire.CompletionListener() {
                    @Override
                    public void onComplete(String key, DatabaseError error) 
{

                        if (myCurrentMarker != null)
                            myCurrentMarker.remove();

//                            mMap.addMarker(new 
MarkerOptions().position(latLng).title("Your location"));
//                            
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

                        getLatitude(latitude);
                        getLongitude(getLongitude(longitute));


                        Toast.makeText(getActivity(), latitude + " " 
+longitute, Toast.LENGTH_SHORT).show();
                    }
                });

    }

}

public static double getLatitude(double lat) {
    return lat;
}

public static double getLongitude(double lng) {
    return lng;
}

private void creatLocationRequest() {
    mlocationRequest = new LocationRequest();
    mlocationRequest.setInterval(UPDATE_INTERVAL);
    mlocationRequest.setFastestInterval(FASTEST_INTERVAL);
    mlocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mlocationRequest.setSmallestDisplacement(DISPLACEMENT);
}

private void buildGoogleApiClient() {
    mgoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mgoogleApiClient.connect();
}

private boolean checkPlaySercives() {
    int resultCode = 
GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
            GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(), 
PLAY_SERVICES_RESOLUTION_REQUEST).show();
        else {
            Toast.makeText(getActivity(), "This device is not supported", 
Toast.LENGTH_LONG).show();
        }
        return false;
    }
    return true;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
}

@Override
public void onLocationChanged(Location location) {
    mlastlocation = location;
    displayLocation();

}

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

@Override
public void onConnected(@Nullable Bundle bundle) {
    displayLocation();
    startLocationUpdates();
}

private void startLocationUpdates() {
    if (ActivityCompat.checkSelfPermission(getActivity(), 
android.Manifest.permission.ACCESS_COARSE_LOCATION) != 
PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(getActivity(), 
android.Manifest.permission.ACCESS_FINE_LOCATION) != 
PackageManager.PERMISSION_GRANTED) {
        return;
    }

LocationServices.FusedLocationApi.requestLocationUpdates(mgoogleApiClient, 
mlocationRequest, this);
}

@Override
public void onConnectionSuspended(int i) {
    mgoogleApiClient.connect();
}

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

}

//    @Override
//    public void onResume() {
//        mapView.onResume();
//        super.onResume();
//    }

@Override
public void onDestroy() {
    super.onDestroy();
    mapView.onDestroy();
}

@Override
public void onLowMemory() {
    super.onLowMemory();
    mapView.onLowMemory();
}
}

This code was working on activity very nicely but doing problem in tab layout viewpager.

Thank you in advance!

Ricardo
  • 9,136
  • 3
  • 29
  • 35
  • 1
    do you get any errors in logcat? Are you sure you are using correct API key? – Vladyslav Matviienko Mar 22 '18 at 11:49
  • yes. before using tab layouts i was doing same work on activity then it was working. – Daniyal Saeed Mar 22 '18 at 11:52
  • https://stackoverflow.com/a/42198711/6527039 refer this – Liya Mar 22 '18 at 11:53
  • i commented these 2 lines in my code mMap.addMarker(new MarkerOptions().position(latLng).title("Your location")); mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); because then i was getting this exception. Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference – Daniyal Saeed Mar 22 '18 at 11:54
  • @Liya i am already getting current what i want is to current user location inside the tab layout. Please see that png link which i attached top of this post. – Daniyal Saeed Mar 22 '18 at 12:00

1 Answers1

1

MapView in XML

<com.google.android.gms.maps.MapView
            android:id="@+id/my_test_map"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

Java code:

private MapView mMapView;
private GoogleMap mGoogleMap;
...
...

private void setUpMapIfNeeded() {

    if (mGoogleMap == null) {
        mMapView = (MapView) findViewById(R.id.my_test_map);
        mMapView.onCreate(getArguments());
        mMapView.onResume();

        try {
            MapsInitializer.initialize(getActivity());
            final GoogleMap.OnMarkerClickListener markerClickListener = this;
            mMapView.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(GoogleMap gmap) {
                    mGoogleMap = gmap;
                    mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

                    //fill markers
                    //add marker listener 

                }
            });



        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

This sample code from one of my project that works fine with viewpager that in a fragment.

When I review your code there is one row that you was forget to call.

mMapView.onResume();

add this line under your mapView.onCreate(savedInstanceState);

Twinsens
  • 417
  • 6
  • 23
  • but not now i'm getting this error. java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference at com.example.daniyal.socialmap.MapFragment$1.onComplete(MapFragment.java:141) – Daniyal Saeed Mar 22 '18 at 12:37
  • You have to add your markers inside 'OnMapReady' method. Please review my example code. I was commented two line of information. //Fill markers and //add marker listener. In order to make it easier for who are in trouble to find the answer this, could you pls mark the answer as a 'Answer' (For green thick) ;) – Twinsens Mar 22 '18 at 12:40
  • it's just show me map. and even it doesn't showing toast from onMapReady(). its showing toast of latitude and longitude from displayLocation(). – Daniyal Saeed Mar 22 '18 at 14:17
  • You have to use main thread when you doing something with UI elements. Showing, dismissing, animating etc. Do you UI transaction on UI Thread. If you wanna show toast in onMapReady method You will use this runOnUiThread(new Runnable() { @Override public void run() { //SHOW Toast } }); – Twinsens Mar 22 '18 at 14:20