I am adding SupportMapFragment programmatically to my main activity.
I am able to add it but i need a edit text and a button also to be displayed at the top of the map.
I have created a separate layout for my map fragment which i add programmatically inside my main activity. But i get a NPE saying "Unable to resume activity"
Please help me.
Here is my code . MainActivity.java
public class MainActivity extends FragmentActivity{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
GoogleMap googleMap;
String lat;
String provider;
protected double latitude,longitude;
protected boolean gps_enabled,network_enabled;
private ImageView mImage;
List<Marker> markerslist = new ArrayList<Marker>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get an instance of FragmentTransaction from your Activity
final FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//add a fragment
MapFragmentActivity mapFragment = new MapFragmentActivity();
fragmentTransaction.replace(R.id.appfragment, mapFragment);
fragmentTransaction.commit();
mImage = (ImageView)findViewById(R.id.eemaView);
mImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("inside on click eema");
EnterpriseFragment entFragment = new EnterpriseFragment();
FragmentTransaction fragmentTrans = fragmentManager.beginTransaction();
fragmentTrans.replace(R.id.appfragment, entFragment);
fragmentTrans.commit();
}
});
mImage = (ImageView)findViewById(R.id.deviationView);
mImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("inside on click deviation");
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//add a fragment
MapFragmentActivity mapFragment = new MapFragmentActivity();
fragmentTransaction.replace(R.id.appfragment, mapFragment);
fragmentTransaction.commit();
}
});
}
Here is my fragment class
public class MapFragmentActivity extends SupportMapFragment implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
GoogleMap googleMap;
String lat;
String provider;
protected double latitude,longitude;
protected boolean gps_enabled,network_enabled;
List<Marker> markerslist = new ArrayList<Marker>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.mapfragmentlayout, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
googleMap = this.getMap();
if (googleMap != null) {
//Your initialization code goes here
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
// Getting reference to btn_find of the layout activity_main
//Button btn_find = (Button) getActivity().findViewById(R.id.btn_find);
// Defining button click event listener for the find button
View.OnClickListener findClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Getting reference to EditText to get the user input location
EditText etLocation = (EditText) getActivity().findViewById(R.id.et_location);
// Getting user input location
String location = etLocation.getText().toString();
if(location!=null && !location.equals("")){
for(Marker m : markerslist) {
System.out.println("Marker size is "+markerslist.size());
System.out.println("Title is "+m.getSnippet());
System.out.println("Position is "+((LatLng)(m.getPosition())).latitude);
if(location.equals(m.getSnippet())) {
// do something with the marker
LatLng latLng = m.getPosition();
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
break; // stop the loop
}
}
}
}
};
// Setting button click event listener for the find button
//btn_find.setOnClickListener(findClickListener);
googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// Getting view from the layout file info_window_layout
View v = getActivity().getLayoutInflater().inflate(R.layout.site_info_window, null);
List<String> qfList = JSONReader.readQuickFixData(getActivity());
ListView devLst = (ListView)v.findViewById(R.id.deviationList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),R.layout.simple_list_item_deviation,android.R.id.text1,qfList);
devLst.setAdapter(adapter);
return v;
}
});
}
}
This is my fragment layout 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">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/btn_find"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Find"
android:layout_alignParentRight="true" />
<EditText
android:id="#+id/et_location"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="Enter Site ID"
android:layout_toLeftOf="#id/btn_find" />
</RelativeLayout>
<fragment 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"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
</LinearLayout>
My main layout xml
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="WEM App"
android:id="#+id/textView"
android:textStyle="bold"
android:textSize="16sp"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:layout_margin="3dp"
android:textColor="#color/abc_input_method_navigation_guard"
android:background="#android:color/holo_green_light"/>
<LinearLayout
android:id="#+id/appfragment"
android:layout_width="match_parent"
android:layout_weight="4"
android:layout_height="0dip"
android:orientation="horizontal">
</LinearLayout>
<HorizontalScrollView
android:id="#+id/hsview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginBottom="3dp"
android:background="#android:color/holo_green_light">
<LinearLayout android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/deviationView"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/sema_icon" />
<ImageView
android:id="#+id/eemaView"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/eema_icon" />
<ImageView
android:id="#+id/siteView"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/sema_icon" />
<ImageView
android:id="#+id/alertsView"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/eema_icon" />
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
Make sure u r using import android.support.v4.app.Fragment; and import android.support.v4.app.FragmentTransaction;
Make changes as below -
change public class MapFragmentActivity extends SupportMapFragment
to public class MapFragmentActivity extends Fragment keep rest as it is.
Related
i'm using a map in a fragment but as shown on the following screenshot, the map doesn't apear. I made sure i have an internet connection and a gps signal so i don't think it's a connectivity problem.
Here is the code from my fragment:
public class MapViewFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.location_fragment, container, false);
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView = rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// For showing a move to my location button
googleMap.setMyLocationEnabled(true);
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(-34, 151);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
return rootView;
}
#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();
}
}
And here is the xml file of the fragment:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.google.android.gms.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
I am then inserting this fragment into my main activity layout using the following procedure:
public void addFragment(Fragment fragment, boolean addToBackStack, String tag) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (addToBackStack) {
ft.addToBackStack(tag);
}
ft.replace(R.id.container_frame_back, fragment, tag);
ft.commitAllowingStateLoss();
}
XML file of my MainActivity
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<Button
android:id="#+id/btn1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Fragment 1 " />
</LinearLayout>
<LinearLayout
android:id="#+id/container_frame_back"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="56dp"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"></LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
So i don't really get why i have no map showing up, i don't think it's a permissions problem either, iv'e already worked with maps in previous projects but this time it's just not showing up for some reason... Thank you for any reply!
Problem solved, it turns out that error messages related to permissions aren't displayed in the logs when you test your app on an external device. I had problems with permissions in my maps fragment. I just added the following code and it worksjust fine:
String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
requestPermissions(perms, 0); // Use this method in Fragment classes
I am trying to implement PlaceAutoCompleteFragment inside a fragment. I have end up with this (based on the accepted answer of this question):
public class SecondFragment extends Fragment
implements OnMapReadyCallback {
PlaceAutocompleteFragment placeAutoComplete;
.....
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.fragment_second, null, false);
// Create Map
if (savedInstanceState != null) {
mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
latlang.Lat = mLastKnownLocation.getLatitude();
latlang.Lang = mLastKnownLocation.getLongitude();
}
// Construct a FusedLocationProviderClient.
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
getLocationPermission();
getDeviceLocation();
placeAutoComplete = (PlaceAutocompleteFragment) getActivity().getFragmentManager().findFragmentById(R.id.place_autocomplete);
placeAutoComplete.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
Log.d("Maps", "Place selected: " + place.getName());
}
#Override
public void onError(Status status) {
Log.d("Maps", "An error occurred: " + status);
}
});
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//Search Place
return view;
}
and the corresponding layout is:
<LinearLayout 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=".SecondFragment"
android:orientation="vertical"
android:weightSum="1">
<fragment
android:id="#+id/place_autocomplete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
/>
<fragment
android:id="#+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
So, I got a searchbar which, on click opens up and keyboard flashes for a second and then crashes, before I start typing, and returns to "before click" view.
Whats going wrong here?
My application shows blank google map on a fragment. I just call that fragment from MainActivity. I have searched/read on google, but none did help me at. I am not getting any error and I have used proper APIs Keys.
The following are my classes/mxls:
public class MainActivity extends AppCompatActivity {
private Button map_me;
private Button bCordinates;
public static Location mLastKnownLocation;
private FusedLocationProviderClient mFusedLocationProviderClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try {
if (true) {
Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful()) {
//Get the Location of the current device
mLastKnownLocation = task.getResult();
}
}
});
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
bCordinates = (Button)findViewById(R.id.bcordinates);
bCordinates.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Toast.makeText(getApplicationContext(),""+mLastKnownLocation.getLatitude()+" , " +
" "+mLastKnownLocation.getLongitude(),Toast.LENGTH_LONG).show();
}
});
map_me = (Button)findViewById(R.id.bmap);
map_me.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyMapFragment myMapFragment = new MyMapFragment();
fragmentTransaction.add(R.id.fragment_container, myMapFragment);
fragmentTransaction.commit();
}
});
}
}
public class MyMapFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap googleMap;
private MapView mapView;
private View view;
private FusedLocationProviderClient mFusedLocationProviderClient;
public MyMapFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.map_layout, container, false);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mapView = (MapView) getView().findViewById(R.id.map);
if(mapView!=null)
{
mapView.onCreate(null);
mapView.onResume();
mapView.getMapAsync(this);
}
}
#Override
public void onMapReady(final GoogleMap mGoogleMap) {
{
googleMap = mGoogleMap;
LatLng mLatLng = new LatLng(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude());
googleMap.addMarker(new MarkerOptions().position(mLatLng).title("You're here"));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mLatLng,15));
mapView.onResume();
}
}
}
map fragment layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".MyMapFragment">
<com.google.android.gms.maps.MapView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
/>
</FrameLayout>
main activity layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context="com.bdushimi.android2.MainActivity"
>
<Button
android:id="#+id/bmap"
android:layout_width="88dp"
android:layout_height="wrap_content"
android:text="MAP Me!"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginStart="8dp"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintHorizontal_bias="0.067"
tools:layout_editor_absoluteY="32dp" />
<Button
android:id="#+id/btext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEXT ME!"
tools:layout_editor_absoluteY="32dp"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintHorizontal_bias="0.464" />
<Button
android:id="#+id/bcordinates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cordinates"
android:layout_marginEnd="8dp"
tools:layout_editor_absoluteY="32dp"
android:layout_marginRight="28dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintHorizontal_bias="0.949"
app:layout_constraintLeft_toLeftOf="parent" />
<LinearLayout
android:id="#+id/fragment_container"
android:layout_width="333dp"
android:layout_height="370dp"
android:orientation="vertical"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="125dp"
app:layout_constraintHorizontal_bias="0.514"></LinearLayout>
</android.support.constraint.ConstraintLayout>
Please, help me to find out what I am doing wrong.
I think you should use MapFragment or SupportMapFragment in your map layout xml file according to your usability.
For now :
Replace :
with :
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/headerLayout"
tools:context="com.dxs.rnf.winwin.main.ui.fragments.DashboardMapFragment"
android:name="com.google.android.gms.maps.MapFragment"/>
Note : Also check your GOOGLE_API_KEY
I have a small map view in my contacts activity:
But I don't know how to move the camera to a specific location, I've done it before on a MapActivity, but don't know how to do it in here. I don't know where to use the moveCamera function because there is no onMapReady like in a MapActivity, appreciate any help guys. The code:
Java:
public class Contacts extends AppCompatActivity {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Contactos");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.LinearLayoutCompat 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"
tools:context="com.example.abili.agriexport2.Contacts">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="25dp"
android:orientation="vertical"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="0dp">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.20">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textView7"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="25dp"
android:layout_weight="1"
android:text="Onde Estamos:"
android:textSize="18sp" />
<fragment
android:id="#+id/miniMap"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_weight="8" />
</LinearLayout>
</ScrollView>
</LinearLayout>
</android.support.v7.widget.LinearLayoutCompat>
Try this:
in xml:
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
in code: Declare
static final LatLng Your_Location = new LatLng(23.81, 90.41); //Your LatLong
private GoogleMap mMap;
then inside OnCreate()
((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Your_Location, 15)); //move camera to location
if (mMap != null) {
Marker hamburg = mMap.addMarker(new MarkerOptions().position(Your_Location));
}
// Rest of the stuff you need to do with the map
}
});
#alb You can use the same implementaion as you mentioned you have worked with onMapReadyCallback.
Here are some changes in your code as you have not instantiated the map it is displaying default view
public class Contacts extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Contactos");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.miniMap);
mapFragment.getMapAsync(this);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.clear();
//Here locate and move your camera as required
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(locationLatLng, 16.0f));
}
}
Update xml by replacing the map fragment
<fragment
android:id="#+id/miniMap"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_weight="8"
/>
Try this code:
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Latitude, Longitude), 18));
As your map is pretty static you can get a cleaner code if you add the camera target and zoom to your XML. Simply add this to your <fragment> in your layout.xml (changing the coordinates and zoom level to suit your needs):
xmlns:map="http://schemas.android.com/apk/res-auto"
map:cameraTargetLat="40"
map:cameraTargetLng="-4"
map:cameraZoom="18"
tools:ignore="MissingPrefix"
Note: you need the tools:ignore="MissingPrefix" line to fix this Unexpected namespace "map" - Android Google Maps API
Write listener to mapfragment
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.miniMap);
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
//write your moveCamera function here
}
});
Try using LocationManager and create marker in onLocationChanged listener
public void onLocationChanged(Location location) {
final LatLng latlng = new LatLng(location.getLatitude(),location.getLongitude());
createMarker(latlng);
}
private void createMarker(LatLng latlng) {
MarkerOptions markerOptions = null;
try {
markerOptions = new MarkerOptions().position(latlng).title("Title");
} catch (IOException e) {
e.printStackTrace();
}
final Marker marker = googleMap.addMarker(markerOptions);
}
After creating marker, I have used below code to animate marker when camera is moved:
final LatLngInterpolator latLngInterpolator = new LatLngInterpolator.LinearFixed();
final LatLng startPosition = marker.getPosition();
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final Interpolator interpolator = new LinearInterpolator();
final float durationInMs = 3000;
handler.post(new Runnable() {
long elapsed;
float t;
float v;
#Override
public void run() {
// Calculate progress using interpolator
elapsed = SystemClock.uptimeMillis() - start;
t = elapsed / durationInMs;
v = interpolator.getInterpolation(t);
marker.setPosition(latLngInterpolator.interpolate(v, startPosition, googleMap.getCameraPosition().target));
if (t < 1) {
// Post again 16ms later.
handler.postDelayed(this, 16);
}
}
});
I am trying to switch fragments after login, I have MainActivity that for the first time add the LogIn Fragment to his content, after the user login, I want to switch to a Google map Fragment.
How can I create a Google Map class extending Fragment and not FragmentActivity or Activity?
Can I add FragmentActivity to the layout of the MainActivity?
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public class YS_MapFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public YS_MapFragment() {
// Empty constructor required for fragment subclasses
}
MarkerOptions markerOptions;
LatLng latLng;
String locationString;
MapView mapView;
GoogleMap googleMap;
private String tag = "TAG";
private String msg = "= ";
// GPSTrackerN class
GPSTracker gps;
double latitude = 0.0, longitude = 0.0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mainLayout = inflater.inflate(R.layout.fragment_map, container,false);
locationString = getArguments().getString("location");
latitude = getArguments().getDouble("Lat");
longitude = getArguments().getDouble("Long");
// Gets the MapView from the XML layout and creates it
mapView = (MapView) mainLayout.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
// Gets to GoogleMap from the MapView and does initialization stuff
googleMap = mapView.getMap();
googleMap.getUiSettings().setMyLocationButtonEnabled(false);
googleMap.setMyLocationEnabled(true);
// Needs to call MapsInitializer before doing any CameraUpdateFactory
// calls
MapsInitializer.initialize(this.getActivity());
if (locationString != null && !locationString.equals(""))
{
getLocation(latitude, longitude);
} else {
getCurrentLocation();
}
return mainLayout;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
<RelativeLayout
android:id="#+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<com.google.android.gms.maps.MapView
android:id="#+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="40dip" >
</com.google.android.gms.maps.MapView>
I tried instantiating the map directly in the xml but it got me a lot of problems when trying to do more complex things with the fragments and the navigation.
The solution that gave me the best results is something like this:
1- Have an empty FrameLayout in my view's xml:
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/color_separator" >
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:id="#+id/mapframe" />
</RelativeLayout>
2- Instantiate the SupportMapFragment in my Fragment class and add it to the FrameLayout:
if(mMapFragment==null) {
mMapFragment = SupportMapFragment.newInstance();
FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.mapframe, mMapFragment);
fragmentTransaction.commit();
}
3- Get the map asynchronically:
mMapFragment.getMapAsync(this);
(...)
#Override
public void onMapReady(GoogleMap googleMap) {
//THIS IS JUST EXAMPLE CODE; PUT WHATEVER STUFF YOU NEED HERE
mMap=googleMap;
googleMap.addMarker(new MarkerOptions().position(endLatLng).title(getString(R.string.title)));
mMapFragment.getView().setVisibility(View.GONE);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
new LatLng(endLatLng.latitude, endLatLng.longitude), 15);
googleMap.animateCamera(cameraUpdate);
}
This has worked perfectly for me.