Reputation: 21
I want to have a mapview like this suppose my main activity is like this
Here my main activity holds the instance of mapview in main activity and then when I click on it ,then a new activity should be opened with the map activity in android
Upvotes: 0
Views: 2139
Reputation: 1096
You need to have the supportMapFragment in your xml file and get the reference of mapFragment into your MainFragment. The below code explains, How I accomplished the MapView inside Fragment. Write the below XML code in the mapView.xml and then Use the Fragment OnCreateView to get references.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainMap"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="200dp"
/>
public class MapInFragment extends Fragment implements OnMapReadyCallback {
private View rootView;
private GoogleMap mMap;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.mapView, container, false);
try{
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mainMap);
mapFragment.getMapAsync(MapInFragment.this);
}catch (Exception e){
e.printStackTrace();
}
return rootView;
}
@Override
public void onMapReady(GoogleMap googleMap) {
try {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng croplatlng = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
mMap.addMarker(new MarkerOptions().position(croplatlng).title(crop + "Field"));
//mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(croplatlng,16));
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(croplatlng , 16);
//mMap.addMarker(new MarkerOptions().position(location).title(""));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation ));
mMap.animateCamera(cameraUpdate,2000,null);
}catch (Exception e){
e.printStackTrace();
}
}
public void onDestroyView()
{
try {
Fragment fragment = (getChildFragmentManager().findFragmentById(R.id.mainMap));
if (fragment != null) {
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}
}catch (Exception e){
e.printStackTrace();
}
super.onDestroyView();
}
}
Upvotes: 1
Reputation: 400
Step 1: Add Mapview on your main activity.
Step 2: Add OnClickListener on MapView
mMapView.getMap().setOnMapClickListener(new OnMapClickListener()
{
@Override
public void onMapClick(LatLng arg0)
{
//Open New Activity
}
});
Step 3: Open New Activiy to show your map.
Hope you will find this answer usefull. Happy Coading
Upvotes: 1