I cannot add markers to my map using the recommended documentation, I have no errors however markers are not appearing on the map.
I have tried the following:
gmap = googleMap;
gmap.setMinZoomPreference(12);
LatLng ny = new LatLng(40.7143528, -74.0059731);
gmap.moveCamera(CameraUpdateFactory.newLatLng(ny));
and
gmap.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
Neither of these are working.
Here is my main activity,
private static MapView mapView;
private GoogleMap gmap;
private static final String MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey";
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
session = new SessionHandler(getApplicationContext());
final User user = session.getUserDetails();
final View background = findViewById(R.id.home_background_view);
final ViewPager viewPager = (ViewPager) findViewById(R.id.home_view_pager);
MainPagerAdapter adapter = new MainPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
final int colourGreen = ContextCompat.getColor(this, R.color.Green);
final int colourPink = ContextCompat.getColor(this, R.color.Pink);
final int colourBlue = ContextCompat.getColor(this, R.color.CafeSeaBlue);
TabLayout tabLayout = (TabLayout) findViewById(R.id.am_tab_layout);
tabLayout.setupWithViewPager(viewPager);
loadLocations();
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.map);
// mapFragment.getMapAsync(this);
viewPager.setCurrentItem(1);
//mapView = findViewById(R.id.mapView);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//if on first screen
if (position == 0)
{
background.setBackgroundColor(colourBlue);
//background.setAlpha(1-positionOffset);
}
//if on mid screen
else if (position == 1) {
background.setBackgroundColor(colourPink);
//background.setAlpha(positionOffset);
}
//if on last screen
else if (position == 2) {
background.setBackgroundColor(colourGreen);
//background.setAlpha(1+positionOffset);
}
}
#Override
public void onPageSelected(int position) {
if(position == 0)
{
}if(position == 2){
// gmap.addMarker(new MarkerOptions()
// .position(new LatLng(50, 50))
// .title("Hello world"));
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onLocationChanged(Location location) {
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
globalLat = location.getLatitude();
globalLong = location.getLongitude();
Log.d("Location","Longitude = "+currentLongitude);
Log.d("Location","Latitude = "+currentLatitude);
if(tv1 != null)
tv1.setText(Double.toString(currentLatitude));
if(tv2 != null)
tv2.setText(Double.toString(currentLongitude));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
//progress bar
private void displayLoader() {
pDialog = new ProgressDialog(HomeActivity.this);
pDialog.setMessage("Loading.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAP_VIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAP_VIEW_BUNDLE_KEY, mapViewBundle);
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
}
#Override
public void onMapReady(GoogleMap map) {
gmap.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
}
}
And my layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
tools:background="#color/CafeSeaBlue"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools">
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="80dp"
android:background="#drawable/card_background" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/latText1"
android:layout_width="match_parent"
android:layout_height="32dp"
android:layout_below="#+id/longText"
android:layout_marginTop="100dp"
android:layout_marginBottom="50dp"
android:background="#color/White"
android:text="Map Screen"
android:textAlignment="center"/>
<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"
android:layout_marginTop="150dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="40dp"
tools:context=".HomeActivity"
/>
</FrameLayout>
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.map);
// mapFragment.getMapAsync(this);
having this uncommented in the section it is currently in crashes it unexpectedly, saying null object reference
The map itself loads however I cannot get pins on it. I have tried so many methods and probably have quite a bit of unnecessary code.
The map displays on the screen, i would attach an image but i require 10 points before I am able to. I cannot add markers to my map using the recommended documentation, I have no errors however markers are not appearing on the map.
I have tried the following:
gmap = googleMap;
gmap.setMinZoomPreference(12);
LatLng ny = new LatLng(40.7143528, -74.0059731);
gmap.moveCamera(CameraUpdateFactory.newLatLng(ny));
and
gmap.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
Neither of these are working.
Here is my main activity,
private static MapView mapView;
private GoogleMap gmap;
private static final String MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey";
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
session = new SessionHandler(getApplicationContext());
final User user = session.getUserDetails();
final View background = findViewById(R.id.home_background_view);
final ViewPager viewPager = (ViewPager) findViewById(R.id.home_view_pager);
MainPagerAdapter adapter = new MainPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
final int colourGreen = ContextCompat.getColor(this, R.color.Green);
final int colourPink = ContextCompat.getColor(this, R.color.Pink);
final int colourBlue = ContextCompat.getColor(this, R.color.CafeSeaBlue);
TabLayout tabLayout = (TabLayout) findViewById(R.id.am_tab_layout);
tabLayout.setupWithViewPager(viewPager);
loadLocations();
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.map);
// mapFragment.getMapAsync(this);
viewPager.setCurrentItem(1);
//mapView = findViewById(R.id.mapView);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//if on first screen
if (position == 0)
{
background.setBackgroundColor(colourBlue);
//background.setAlpha(1-positionOffset);
}
//if on mid screen
else if (position == 1) {
background.setBackgroundColor(colourPink);
//background.setAlpha(positionOffset);
}
//if on last screen
else if (position == 2) {
background.setBackgroundColor(colourGreen);
//background.setAlpha(1+positionOffset);
}
}
#Override
public void onPageSelected(int position) {
if(position == 0)
{
}if(position == 2){
// gmap.addMarker(new MarkerOptions()
// .position(new LatLng(50, 50))
// .title("Hello world"));
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onLocationChanged(Location location) {
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
globalLat = location.getLatitude();
globalLong = location.getLongitude();
Log.d("Location","Longitude = "+currentLongitude);
Log.d("Location","Latitude = "+currentLatitude);
if(tv1 != null)
tv1.setText(Double.toString(currentLatitude));
if(tv2 != null)
tv2.setText(Double.toString(currentLongitude));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
//progress bar
private void displayLoader() {
pDialog = new ProgressDialog(HomeActivity.this);
pDialog.setMessage("Loading.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAP_VIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAP_VIEW_BUNDLE_KEY, mapViewBundle);
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
}
#Override
public void onMapReady(GoogleMap map) {
gmap.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
}
}
And my layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
tools:background="#color/CafeSeaBlue"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools">
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="80dp"
android:background="#drawable/card_background" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/latText1"
android:layout_width="match_parent"
android:layout_height="32dp"
android:layout_below="#+id/longText"
android:layout_marginTop="100dp"
android:layout_marginBottom="50dp"
android:background="#color/White"
android:text="Map Screen"
android:textAlignment="center"/>
<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"
android:layout_marginTop="150dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="40dp"
tools:context=".HomeActivity"
/>
</FrameLayout>
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.map);
// mapFragment.getMapAsync(this);
having this uncommented in the section it is currently in crashes it unexpectedly, saying null object reference
The map itself loads however I cannot get pins on it. I have tried so many methods and probably have quite a bit of unnecessary code.
I would attach an image of the displaying and interatable map here but I do not have 10 points.
https://i.imgur.com/mpp9aAY.png
It appears that you are focusing your map on the NY City area, but are pinning your marker in the middle of Nigeria. Are you sure that the marker is not successfully added? Try setting your marker near where you position the map focus.
mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
these codes are necessary, else you won't get any callback to
onMapReady(GoogleMap googleMap) {}
I think the crash occurs because the variable gmap is not initialised. Just add gmap = map before adding the marker in the onMapReady.
Related
Fragment for map:
public class DashboardFragment extends Fragment implements OnMapReadyCallback {
GoogleMap mGoogleMap;
MapView mMapView;
View mView;
private RequestQueue queue;
public DashboardFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
queue = Volley.newRequestQueue(getActivity().getApplicationContext());
getEarthQuakes();
}
OnCreateView, OnViewcreated:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.fragment_dashboard, container, false);
return mView;
}
#Override
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMapView = (MapView) mView.findViewById(R.id.map);
if (mMapView != null) {
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync((OnMapReadyCallback) this);
}
}
OnMapReady:
#Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(getContext());
mGoogleMap = googleMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
/*googleMap.addMarker(new MarkerOptions().position(new LatLng(43.84864, 18.35644)).title("Sarajevo"));
CameraPosition Sarajevo = CameraPosition.builder().target(new LatLng(43.84864, 18.35644)).zoom(10).bearing(0).tilt(45).build();
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(Sarajevo));*/
}
Sometimes the application stops, and sometimes it works okey.
public void getEarthQuakes() {
final Earthquake earthquake = new Earthquake();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, Constants.URL,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray features = response.getJSONArray("features");
for ( int i=0; i<Constants.LIMIT;i++){
JSONObject properties = features.getJSONObject(i).getJSONObject("properties");
JSONObject geometry = features.getJSONObject(i).getJSONObject("geometry");
JSONArray coordinates = geometry.getJSONArray("coordinates");
double lon = coordinates.getDouble(0);
double lat = coordinates.getDouble(1);
Log.d("Quake", lon + ", " + lat);
When the application doesn't work this is printed in the console: 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
earthquake.setPlace(properties.getString("place"));
earthquake.setType(properties.getString("type"));
earthquake.setTime(properties.getLong("time"));
earthquake.setMagnitude(properties.getDouble("mag"));
earthquake.setDetailLink(properties.getString("detail"));
java.text.DateFormat dateFormat = java.text.DateFormat.getDateInstance();
Date date;
String formattedDate= dateFormat.format(new Date(Long.valueOf(properties.getLong("time"))));
Add markers:
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
markerOptions.title(earthquake.getPlace());
markerOptions.position(new LatLng(lat,lon));
markerOptions.snippet("Magnitude: " +
earthquake.getMagnitude() + "\n" +
"Date: " + formattedDate);
Marker marker = mGoogleMap.addMarker(markerOptions);
// Marker marker= mGoogleMap.addMarker(markerOptions.position(new LatLng(lat,lon)));
marker.setTag(earthquake.getDetailLink());
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon),1));
}
End of code:
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(jsonObjectRequest);
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".ui.dashboard.DashboardFragment">
<com.google.android.gms.maps.MapView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
I was facing the same problem and I solved it by deleting this line: "android:paddingTop="?attr/actionBarSize" in my activity_main.xml.
Before:
With action bar size
After:
Without action bar size
I'm new in coding and I'm trying to make my first app so I say sorry in advance if it could sound stupid to the most.
My app should basically recollect datas (Edit Text) from the add client Activity and show markers in the map Activity.
To do this I thought to put all the informations in Array and then show it on the map.
The question is "how can I do that?" everything I do gives me lots of errors :/
This is where I'm stuck
MapsActivity.java
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
{
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location lastLocation;
private static final int Request_User_Location_Code = 99;
private Button button;
public MapsActivity() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkUserlLocationPermission();
}
// 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);
//set onclicklistener on the button
button = (Button) findViewById(R.id.btnAddClient);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent =new Intent(MapsActivity.this,AddClient.class);
startActivity(intent);
}
});
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mMap = googleMap;
//Asking for permission and set current location
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
//Checking permission
private boolean checkUserlLocationPermission()
{
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
}
return false;
}
else
{
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
switch (requestCode)
{
case Request_User_Location_Code:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
if (googleApiClient == null)
{
buildGoogleApiClient();
}
mMap.setBuildingsEnabled(true);
}
}
else
{
Toast.makeText(this,"DENIED", Toast.LENGTH_SHORT).show();
}
return;
}
}
protected synchronized void buildGoogleApiClient()
{
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
public void onLocationChanged(Location location)
{
lastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate center=CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(16);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
if (googleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}
//Set interval location
#Override
public void onConnected(#Nullable Bundle bundle)
{
locationRequest = new LocationRequest();
locationRequest.setInterval(1100);
locationRequest.setFastestInterval(1100);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
activity_map.xml
<?xml version="1.0" encoding="utf-8"?>
<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=".MapsActivity" >
<Button
android:id="#+id/btnAddClient"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp"
android:background="#drawable/mybutton"
android:text="Add client"
/>
</fragment>
AddClient.java
public class AddClient extends AppCompatActivity {
public Button btnDone;
public EditText name;
public EditText address;
public LatLng latLng;
public GoogleMap mMap;
public Marker marker;
ArrayList<String> clientNames = new ArrayList<>();
ArrayList<String> clientAddress = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addclient);
btnDone = (Button) findViewById(R.id.done_button);
name = (EditText) findViewById(R.id.edit_name);
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clientNames.add(name.getText().toString());
clientAddress.add(address.getText().toString());
getLocationFromAddress();
}
public void getLocationFromAddress(String strAddress) {
//Create coder with Activity context - this
Geocoder coder = new Geocoder(this);
List<Address> address;
try {
//Get latLng from String
address = coder.getFromLocationName(strAddress, 5);
//check for null
if (address == null) {
return;
}
//Lets take first possibility from the all possibilities.
Address location = address.get(0);
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
//Put marker on map on that LatLng
Marker srchMarker = mMap.addMarker(new MarkerOptions().position(latLng).title("name"));
//Animate and Zoon on that map location
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
addclient.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dip"
android:layout_marginBottom="25dip"
android:text="NEW CLIENT DETAILS"
android:textStyle="bold"
android:textSize="30dp"
android:gravity="center_horizontal"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Client name:"
android:textSize="20dp"/>
<EditText
android:id="#+id/edit_name"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:text=""
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dip"
android:text="Client address"
android:textSize="20dp"/>
<EditText
android:id="#+id/edit_lastname"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:text=""
/>
<Button
android:id="#+id/done_button"
android:layout_height="wrap_content"
android:text="DONE"
android:layout_width="130dip"
android:background="#drawable/mybutton"
android:layout_gravity="center"
/>
</LinearLayout>
You should use Google Places API which has an auto complete adapter and predictions for places, below link shows a similar app.
Google-Maps-Google-Places
I managed to implement a TabLayout. Within one of the tabs is a Google Maps Fragment. I want to ask permission to access the user's location and then place a marker on the current location. As of right now, the dialog box does not show up and I do not know why. Can anyone help me?
public class MapsFragment extends Fragment implements OnMapReadyCallback{
GoogleMap mGoogleMap;
MapView mMapView;
View mView;
LocationManager locationManager;
static final int REQUEST_LOCATION = 1;
public MapsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.fragment_maps,container,false);
return mView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
mMapView = (MapView) mView.findViewById(R.id.googleMap);
if(mMapView != null){
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google PLay Services
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
//Location Permission is gratned
MapsInitializer.initialize(getContext());
mGoogleMap.setMyLocationEnabled(true);
}
}
googleMap.addMarker(new MarkerOptions().position(new LatLng(36.652527, -121.797277)).title("CSUMB"));
CameraPosition CSUMB = CameraPosition.builder().target(new LatLng(36.6538, -121.797277)).zoom(16).bearing(0).tilt(45).build();
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(CSUMB));
}
void getLocation(){
locationManager = (LocationManager)getActivity()
.getSystemService(Context.LOCATION_SERVICE);
getLocation();
if(ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
}else{
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!= null){
double latti = location.getLatitude();
double longi = location.getLongitude();
Toast.makeText(getActivity(),"Location is " + String.valueOf(latti) + ", " + String.valueOf(longi),Toast.LENGTH_LONG);
Log.e("Maps Fragment", "Location is: " + String.valueOf(latti) + ", " + String.valueOf(longi));
}
else{
Log.e("Maps fragment", "Unable to find current location.");
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_LOCATION:
getLocation();
break;
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
This is very close to my other answer here, however, that answer doesn't explain how to do it using a ViewPager with a TabLayout.
First, the piece that sets this apart from the other answer, you'll need to keep a reference to the current Fragment in the FragmentPagerAdapter using the instantiateItem() override.
Also, note that the onRequestPermissionsResult() method is needed here in the Activity in order to route the user's permission request response to the Fragment.
Here is the full Activity code:
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
PagerAdapter pagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Get the ViewPager and set it's PagerAdapter so that it can display items
viewPager = (ViewPager) findViewById(R.id.viewpager);
pagerAdapter = new PagerAdapter(getSupportFragmentManager(), MainActivity.this);
viewPager.setAdapter(pagerAdapter);
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
// Iterate over all tabs and set the custom view
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
}
class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[] { "Tab One", "Tab Two", "Tab Three", };
public Fragment[] fragments = new Fragment[tabTitles.length];
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new MapFragment();
case 1:
return new BlankFragment();
case 2:
return new BlankFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
public View getTabView(int position) {
View tab = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
//This populates your Fragment reference array:
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
fragments[position] = createdFragment;
return createdFragment;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
if (requestCode == MapFragment.MY_PERMISSIONS_REQUEST_LOCATION){
MapFragment mapFragment = (MapFragment) pagerAdapter.fragments[0];
if (mapFragment != null) {
mapFragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
android:elevation="6dp">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
android:elevation="0dp" />
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
app:tabMode="fixed"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="0dp"
app:tabTextColor="#d3d3d3"
app:tabSelectedTextColor="#ffffff"
app:tabIndicatorColor="#ff00ff"
android:minHeight="?attr/actionBarSize"
/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
</android.support.design.widget.CoordinatorLayout>
custom_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/custom_text"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="?attr/selectableItemBackground"
android:gravity="center"
android:textSize="16dip"
android:textColor="#ffffff"
android:maxLines="1"
/>
</LinearLayout>
For the Map Fragment, use essentially the same code as the other answer:
public class MapFragment extends SupportMapFragment
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
GoogleMap mGoogleMap;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mGoogleMap == null) {
getMapAsync(this);
}
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
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(ConnectionResult connectionResult) {}
#Override
public void onLocationChanged(Location location)
{
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//optionally, stop location updates if only current location is needed
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(getActivity())
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
Result
First, the location permission prompt:
Once the user has accepted the permission at runtime, show the user's current location:
I am trying to create one flipview which is contain one side Google Map and one side Recyclerview.
I am getting an error while i try i call an Map fragment. it give nullpointer while map has to load at initialization time.
File 1 : fragment_left.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/transparent">
<fragment
android:id="#+id/map_fragment"
android:layout_below="#+id/header"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_above="#+id/footer"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
File 2 : fragment_right.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent"
android:orientation="vertical" >
<android.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/header"
android:background="#mipmap/back"
android:layout_above="#+id/footer"/>
</LinearLayout>
File 3 : flipscreen.xml
<RelativeLayout 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=".flipscreen" >
<RelativeLayout
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#mipmap/gradiant"
android:layout_alignParentTop="true"
android:padding="6dp">
<TextView
android:id="#+id/activity_registration_txtTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="16sp"
android:textStyle="bold"
android:text="#string/events"/>
<ImageView
android:id="#+id/listOfEvent"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#mipmap/menu"/>
</RelativeLayout>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_below="#+id/header"
android:layout_above="#+id/footer"
android:layout_height="wrap_content"
android:layout_centerInParent="true" >
</FrameLayout>
</RelativeLayout>
Java Files
File 1 : flipscreen.java :
public class flipscreen extends FragmentActivity {
private boolean showingBack;
private FragmentLeft left = new FragmentLeft();
private FragmentRight right = new FragmentRight();
private Context context;
private Handler handler;
private FlipAnimation flipAnimation;
private FlipAnimation backFlip;
private GoogleMap map;
private FragmentManager mFragmrg;
List<Event> lsEvent=new ArrayList<Event>();
private double latitude = 0;
private double longitude = 0;
FrameLayout mapLayout;
ImageView flipView;
ImageButton btnAddEvent;
String strUserId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.flipscreen);
context = this;
handler = new Handler(getMainLooper());
mapLayout = (FrameLayout)findViewById(R.id.fragment_container);
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, right, "fragmentRight").commit();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, left, "fragmentLeft").commit();
flipView=(ImageView) findViewById(R.id.listOfEvent);
btnAddEvent=(ImageButton)findViewById(R.id.btnAddEvent);
btnAddEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!(strUserId.equals(""))){
startActivity(new Intent(flipscreen.this,AddEventActivity.class));
// finish();
}else{
startActivity(new Intent(flipscreen.this,LoginActivity.class));
}
}
});
flipView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flipAnimation = new FlipAnimation(left.getView(), right.getView());
backFlip = new FlipAnimation(left.getView(), right.getView());
handler.removeCallbacks(rotate);
handler.postDelayed(rotate, 100);
}
});
}
private Runnable rotate = new Runnable() {
#Override
public void run() {
if (!showingBack) {
left.getView().startAnimation(flipAnimation);
right.getView().startAnimation(flipAnimation);
// Toast.makeText(context, "flip", Toast.LENGTH_LONG).show();
flipView.setImageResource(R.mipmap.nav_map);
showingBack = true;
} else {
showingBack = false;
backFlip.reverse();
// Toast.makeText(context, "backflip", Toast.LENGTH_LONG).show();
left.getView().startAnimation(backFlip);
right.getView().startAnimation(backFlip);
flipView.setImageResource(R.mipmap.menu);
}
}
};
}
File 2 : fragmentLeft.java :
public class FragmentLeft extends Fragment {
private GoogleMap map;
private FragmentManager mFragmrg;
List<Event> lsEvent=new ArrayList<Event>();
private double latitude = 0;
private double longitude = 0;
private SupportMapFragment mMapFragment;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View flipMap =inflater.inflate(R.layout.fragment_left, container,false);
SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
// // Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(latitude, longitude);
map.clear();
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 8);
map.animateCamera(cameraUpdate);
System.out.println("Latitude "+latitude+ " \n Longitude "+longitude);
}
});
return flipMap;
}
}
File 3 : FragmentRight.java :
public class FragmentRight extends Fragment {
private static final String TAG ="NearByActivityList" ;
RecyclerView recyclerView;
List<Event> lsEvent=new ArrayList<Event>();
protected GoogleApiClient mGoogleApiClient;
protected Location mLastLocation;
ImageView listOfEvent;
double latitude = 0;
double longitude = 0;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View fillData =inflater.inflate(R.layout.fragment_right, container,false);
recyclerView = (RecyclerView) fillData.findViewById(R.id.list);
GridLayoutManager manager = new GridLayoutManager(getActivity(), 3);
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
#Override
public int getSpanSize(int position) {
return (3 - position % 3);
}
});
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return fillData;
}
}
My issue is in fragmentLeft.java it's getting null
SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
I have review your code and I think the error is R.id.map, you have not, #+id/map in xml you have #+id/map_fragment:
SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map_fragment)
mapFragment.getMapAsync(new OnMapReadyCallback() {
I found this solution of my problem.. Here is the ans of that.
I found it in https://code.google.com/p/gmaps-api-issues/issues/detail?id=5064 Link.
FragmentLeft.java :
public class FragmentLeft extends Fragment {
private GoogleMap map;
GPSTracker gps;
private SupportMapFragment fragment;
List<Event> lsEvent=new ArrayList<Event>();
private double latitude = 0;
private double longitude = 0;
private GoogleMap mMap;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View flipMap =inflater.inflate(R.layout.fragment_left, container,false);
gps = new GPSTracker(getActivity());
latitude = gps.getLatitude();
longitude = gps.getLongitude();
return flipMap;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getChildFragmentManager();
fragment = (SupportMapFragment) fm.findFragmentById(R.id.map_fragment);
if (fragment == null) {
fragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map_fragment, fragment).commit();
}
}
#Override
public void onResume() {
super.onResume();
if (map == null) {
map = fragment.getMap();
System.out.println("Latitude : = "+latitude+" Longitude : ="+longitude);
map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)));
LatLng sydney = new LatLng(latitude, longitude);
map.clear();
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 12);
map.animateCamera(cameraUpdate);
}
}
}
I'm trying to show a GoogleMap in my App but I get problems right at the beginning of this task.
The line:
SupportMapFragment mapFrag = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
always returns null.
I have tried a lot of things but nothing works. Could you please help me to find the Problem?
Here is my Code:
public class MapSectionFragment extends Fragment implements
ConnectionCallbacks,
OnConnectionFailedListener,
LocationListener,
OnMyLocationButtonClickListener,
OnMapReadyCallback{
private GoogleMap map;
Location location;
GoogleApiClient mGoogleApiClient;
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(5000) // 5 seconds
.setFastestInterval(16) // 16ms = 60fps
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
private void createMapView(){
try{
//here it comes
SupportMapFragment mapFrag = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
map = mapFrag.getMap(); //throws NullPointerException
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_map,
container, false);
createMapView();
return rootView;
}
#Override
public void onPause() {
super.onPause();
mGoogleApiClient.disconnect();
}
#Override
public void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient,
REQUEST,
this); // LocationListener
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
map.setMyLocationEnabled(true);
}
#Override
public boolean onMyLocationButtonClick() {
Toast.makeText(getActivity(), "MyLocation button clicked", Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
}
And here is the XML "fragment_section_map" with the mapID:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="#+id/refresh_map_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="#string/refresh_map" />
<fragment
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
</LinearLayout>
Thanks for your help!
please try this replace
SupportMapFragment mapFrag = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
With
SupportMapFragment mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
because
getChildFragmentManager()
will managing fragments inside an fragment because your are using SupportMapFragment inside a fragment, so please try this solution
Hope this will help you