i want to make maps in android fragment with use extend fragment
this is my code : Maps do not come up, and system force close
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.gmaps, container, false);
SupportMapFragment mapFragment = ((SupportMapFragment) getActivity().getSupportFragmentManager() .findFragmentById(R.id.map));
mapFragment.getMapAsync((OnMapReadyCallback) this.getActivity());
btnFindPath = (Button) view.findViewById(R.id.btnFindPath);
etOrigin = (EditText) view.findViewById(R.id.etOrigin);
etDestination = (EditText) view.findViewById(R.id.etDestination);
btnFindPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendRequest();
}
});
return view;
please help me, and thank you
You can try the below code :
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i("onActivityCreated", "onActivityCreated");
if(supportMapFragment==null){
supportMapFragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
loadMapAtPosition(googleMap, CAMERA_INITIAL_LATITUDE, CAMERA_INITIAL_LONGITUDE);
}
});
}
.....
private void loadMapAtPosition(GoogleMap googleMap, double latitude, double longitude){ googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 6.0f)); }
Just Simple if you want to use Map in Fragment.
Try this
in you Fragment class.
GoogleMap map = ((SupportMapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
and in your xml.
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
if you use google map within fragment then you should be use map
object like this.you have to use getChildFragmentManager() to find
fragment
<fragment
android:id="#+id/main_map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" >
</fragment>
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.main_map);
Related
I new on programming android apps. I want to display a map in one of the fragments that I created for a bottom navigation bar. However, I'm not sure what I should include in the the MainActivity.java, the fragment_map.xml, and the MapFragment.java.
I share my code to see if anyone could please help me to figure it out what I should include in each one.
Thanks :)
MapFragment.java
public class MapFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the layout file as the content view.
setContentView(R.layout.activity_main);
// Get a handle to the fragment and register the callback.
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
private void getMapAsync(MapFragment mapFragment) {
}
private void setContentView(int activity_main) {
}
// Get a handle to the GoogleMap object and display marker.
#Override
public void onMapReady(GoogleMap googleMap) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Marker"));
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private FragmentManager fragmentManager;
private Fragment mapFragment = new MapFragment();
private Fragment storyFragment = new StoryFragment();
private Fragment infoFragment = new InfoFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().add(R.id.body_container, mapFragment, null).commit();
fragmentManager.beginTransaction().add(R.id.body_container, storyFragment, null).commit();
fragmentManager.beginTransaction().add(R.id.body_container, infoFragment, null).commit();
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
//bottomNavigationView.setSelectedItemId(R.id.mapsFragment);
bottomNavigationView.setOnItemSelectedListener(navListener);
}
private NavigationBarView.OnItemSelectedListener navListener = new NavigationBarView.OnItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.nav_map:
fragmentManager.beginTransaction().replace(R.id.body_container, mapFragment).commit();
break;
case R.id.nav_story:
fragmentManager.beginTransaction().replace(R.id.body_container, storyFragment).commit();
break;
case R.id.nav_info:
fragmentManager.beginTransaction().replace(R.id.body_container, infoFragment).commit();
break;
}
return true;
}
};
}
fragment_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"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map"
android:layout_width="wrap_content"
android:layout_height="match_parent"/>
I've been trying to show some info whith info windows -in my app which uses google map- with InfoWindowAdapter but it just does'nt show any pictures so whats the problem?
here's my code for it
public class findonmap extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Bundle recevier=getIntent().getExtras();
float a=recevier.getFloat("x");
float b=recevier.getFloat("y");
LatLng mycordinate = new LatLng(a,b);
mMap.addMarker(new MarkerOptions().position(mycordinate).icon(BitmapDescriptorFactory.
fromResource(R.drawable.marker2)));
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// ConstraintLayout layout=(ConstraintLayout)findViewById(R.id.indo)
View view=getLayoutInflater().inflate(R.layout.info,null);
return view;
}
});
int zoomLevel = 4; //This goes up to 21
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mycordinate, zoomLevel));
}}
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 have made a MapFragment which basically is GoogleMaps. This Fragment is called in an activity, through the fragmentManager and fragment transaction. I would like to tweak my Map now to add some markers and dynamic zoom aswell. I am a bit struggling with this at the moment. Maybe some of you can take a look and help out.
MapsActivity.java
public class MapsActivity extends Activity {
Context context;
Button showMap;
Button showMyLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
context = this;
showMap = (Button)findViewById(R.id.showMap);
showMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
MapFragment mf = new MapFragment();
MapFragment.googleMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble("2.900000"), Double.parseDouble("1.55555")))
.title("oh yeah"));
ft.add(R.id.maps_layout, mf);
ft.commit();
}
});
showMyLocation = (Button)findViewById(R.id.showMyLocation);
showMyLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
MapFragment.java
public class MapFragment extends Fragment {
public static GoogleMap googleMap;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.map_fragment_layout, container, false);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
googleMap = ((com.google.android.gms.maps.MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
}
}
After updating to the code above it gives me this error in the stacktrace :
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.dell.exampleapplication.MapsActivity$1.onClick(MapsActivity.java:42)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5834)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
This may provide extra information for help.
Thanks for you help.
ok here is how i use it:
public class Mapfrag2 extends Fragment{
public static GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.map_fragment_layout, container, false);}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
map = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
if (savedInstanceState == null) {
map.setMyLocationEnabled(true);
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(30.76793169992044, 1.98180484771729));//moving the map to defined position
CameraUpdate zoom = CameraUpdateFactory.zoomTo(5);
map.moveCamera(center);
markerPoints = new ArrayList<LatLng>();
map.animateCamera(zoom);
map.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
//doing something when pressing marker's bubble
}
});
}
}
}
in your activity just call
MapFrag2.map
example
adding markers from activity
Mapfrag2.map.addMarker(new MarkerOptions().position(
new LatLng(Double.parseDouble(lat), Double.parseDouble(lon)))
.title(title).snippet(snippet));
clearing the map
Mapfrag2.map.clear();
Edit 2
try to change this part of code
public void onClick(View v) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
MapFragment mf = new MapFragment();
MapFragment.googleMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble("2.900000"), Double.parseDouble("1.55555")))
.title("oh yeah"));//move this to the end
ft.add(R.id.maps_layout, mf);
ft.commit();
//here you add your marker
}
I found a solution very easy. I just followed the steps in this wiki page (http://www.techotopia.com/index.php/Working_with_the_Google_Maps_Android_API_in_Android_Studio). It basically explains everything to you.
Simple tip: make your MapActivity extend FragmentActivity !
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