I did a tabbed-activity with for tabs. In the fourth tab I did a map, and I added a marker but the marker is not visible and I do not undertand why. I tried many solutions for my problem, but for now I have come to this situation.
This is my Java code:
public class tab_mappa extends SupportMapFragment implements OnMapReadyCallback {
private GoogleMap googleMap;
SupportMapFragment mSupportMapFragment;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
View root = inflater.inflate(R.layout.tabmappa, null, false);
mSupportMapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
if (mSupportMapFragment == null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
mSupportMapFragment = SupportMapFragment.newInstance();
fragmentTransaction.replace(R.id.map, mSupportMapFragment).commit();
}
return root;
}
#Override
public void onMapReady(final GoogleMap googleMap) {
this.googleMap = googleMap;
this.googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
this.googleMap.getUiSettings().setZoomControlsEnabled(true);
this.googleMap.getUiSettings().setCompassEnabled(true);
this.googleMap.getUiSettings().setMyLocationButtonEnabled(true);
this.googleMap.getUiSettings().setZoomGesturesEnabled(true);
this.googleMap.getUiSettings().setRotateGesturesEnabled(true);
LatLng pos1 = new LatLng(44.783878,10.879663);
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(pos1);
this.googleMap.addMarker(new MarkerOptions().position(pos1));
this.googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 100));
}
});
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (googleMap == null) {
getMapAsync(this);
}
}
}
This is my xml code:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:gravity="center"
android:orientation="vertical"
tools:context="esame.progetto.xhondar.github.com.info.tab_mappa">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1.03"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map" />
</LinearLayout>
And this is my final result:
Do you have any ideas?
I solved the problem, this is the solution for those who need it:
Java code:
import android.support.v4.app.Fragment;
public class tab_mappa extends Fragment implements OnMapReadyCallback {
GoogleMap map;
SupportMapFragment mapFragment;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tabmappa, container, false);
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return v;
}
#Override
public void onMapReady(GoogleMap googleMap){
map = googleMap;
this.map = googleMap;
this.map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
this.map.getUiSettings().setZoomControlsEnabled(true);
this.map.getUiSettings().setCompassEnabled(true);
this.map.getUiSettings().setMyLocationButtonEnabled(true);
this.map.getUiSettings().setZoomGesturesEnabled(true);
this.map.getUiSettings().setRotateGesturesEnabled(true);
LatLng pp = new LatLng(44.783878,10.879663);
map.addMarker(new MarkerOptions().position(pp).title("Carpi"));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(pp, 8));
}
}
Xml code:
<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="esame.progetto.xhondar.github.com.info.tab"/>
The error was located in xml code: is Fragment and not FrameLayout, this thing brought conflict within the code.
How about use marker without the builder? you wrote the code in onMapReady()
LatLng pos1 = new LatLng(44.783878,10.879663);
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(pos1);
this.googleMap.addMarker(new MarkerOptions().position(pos1));
this.googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 100));
}
});
it change to
LatLng pos1 = new LatLng(44.783878,10.879663);
googleMap.addMarker(new MarkerOptions().position(pos1));
this.googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 100));
}
});
this one. I removed builder and this before googleMap.
Related
I have a Fragment that contains a map, this map is loaded up on the callback and OnMapReady which pulls in a map at my location successfully.
However I am trying to add in a feature whereby the user selects a location from a Spinner and the selection then draws the relevant Polygon on my map, however I keep getting an error 'Attempting to invoke virtual method Polygon'
I am by no means a talented Android developer, trying to learn and play about somewhat.
public class FindCarpark extends Fragment {
private SupportMapFragment mapFragment;
private UserLocation.OnFragmentInteractionListener mListener;
Spinner spinCar;
String selectedItem;
GoogleMap mMap;
private static final ArrayList<LatLng> cpB = new ArrayList<>();
public FindCarpark() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_find_carpark, container, false);
Context context = getActivity().getApplicationContext();
spinCar = rootView.findViewById(R.id.car_spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),R.array.car_parks, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinCar.setAdapter(adapter);
spinCar.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (i > 0) {
selectedItem = spinCar.getSelectedItem().toString().trim();
addCoords(selectedItem.toString());
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
if (mapFragment == null) {
mapFragment = SupportMapFragment.newInstance();
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
new googleMap().makeMap(mMap);
}
});
}
getChildFragmentManager().beginTransaction().replace(R.id.map, mapFragment).commit();
return rootView;
}
public void addCoords(String coords){
Log.i("coords", coords);
switch (coords){
case "B":
cpB.add(new LatLng(53.797731, -1.546351));
cpB.add(new LatLng(53.797551, -1.545983));
cpB.add(new LatLng(53.797447, -1.545267));
cpB.add(new LatLng(53.797731, -1.546351));
makePolygon(cpB);
Log.i("coords", cpB.toString());
break;
default:
break;
}
}
public void makePolygon(ArrayList<LatLng> coords){
mMap.addPolygon(new PolygonOptions()
.addAll(coords)
.strokeColor(Color.RED)
.fillColor(Color.BLUE));
}
XML:
<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=".FindCarpark">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Spinner
android:id="#+id/car_spinner"
android:prompt="#string/app_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp">
</Spinner>
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</FrameLayout>
Error:
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Polygon com.google.android.gms.maps.GoogleMap.addPolygon(com.google.android.gms.maps.model.PolygonOptions)' on a null object reference
Your mMap variable is never filled. This then later causes a null pointer exception. The problem is:
if (mapFragment == null) {
mapFragment = SupportMapFragment.newInstance();
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
new googleMap().makeMap(mMap);
}
});
}
here mMap is a local variable, while the mMap you later try to access is a property of the object, thus:
if (mapFragment == null) {
mapFragment = SupportMapFragment.newInstance();
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
FindCarpark.this.mMap = mMap
new googleMap().makeMap(mMap);
}
});
}
i Have a Fragment that should show a Specific place on Google Map
public class ContactFragment extends Fragment implements OnMapReadyCallback {
public ContactFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
FragmentManager fragment = getActivity().getSupportFragmentManager();
final SupportMapFragment myMAPF = (SupportMapFragment) fragment.findFragmentById(R.id.map);
return inflater.inflate(R.layout.fragment_contact, container, false);
}
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng marker = new LatLng(34.877737,-1.326545);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(marker,13));
googleMap.addMarker(new MarkerOptions().position(marker));
}
}
and in the XML file of the Fragment i have this :
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
android:layout_below="#+id/contact_domiciliation"
class="com.google.android.gms.maps.MapFragment"
></fragment>
Yet when i launch click on the button that opens this fragment i get a map of the entire globe .
Add this line of code to the fragment:
myMAPF.getMapAsync(this);
I am working on a project in which I need to show a Map in home screen. I used fragment class.
When I first lunch my screen, it is showing map successfully. But when I again click on Home or again come back from another screen to that map screen, below error is showing and app crashes.
"android.view.InflateException: Binary XML file line #57: Error inflating class fragment"
Here is my xml class.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<fragment
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="#+id/homemap"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
map:cameraTilt="50"
map:cameraZoom="40" />
</RelativeLayout>
And below is my Java class
public class Customer_Home_Map extends Fragment {
public Customer_Home_Map() {
}
private GoogleMap theMap;
ProgressDialog progressDialog = null;
ArrayList<SafetyResults_SearchResult> lstresult;
double lati = 0.0, longi = 0.0;
GPSTracker gps;
GoogleMap mMap;
SharedPreferences sharedPreferences;
int locationCount = 0;
API api = API.getInstance();
private HashMap<Marker, MyMarker> mMarkersHashMap;
private ArrayList<MyMarker> mMyMarkersArray = new ArrayList<MyMarker>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// View rootView = inflater.inflate(R.layout.customer_home_map,
// container,
// false);
View view = inflater.inflate(R.layout.customer_home_map,
null);
Typeface tf = Typeface.createFromAsset(getActivity().getAssets(),
up.getFont_Lato_Regular());
gps = new GPSTracker(getActivity());
showAddress();
return view;
}
private void showAddress() {
if (gps.canGetLocation()) {
lati = gps.getLatitude();
longi = gps.getLongitude();
straddress = getMyLocationAddress(lati, longi);
}
mMarkersHashMap = new HashMap<Marker, MyMarker>();
setUpMap();
plotMarkers(mMyMarkersArray);
}
private void plotMarkers(ArrayList<MyMarker> markers) {
if (markers.size() > 0) {
for (MyMarker myMarker : markers) {
// Create user marker with custom icon and other options
MarkerOptions markerOption = new MarkerOptions()
.position(new LatLng(myMarker.getmLatitude(), myMarker
.getmLongitude()));
markerOption.icon(BitmapDescriptorFactory
.fromResource(R.drawable.marker));
Marker currentMarker = mMap.addMarker(markerOption);
mMarkersHashMap.put(currentMarker, myMarker);
mMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());
}
}
}
private void setUpMap() {
// Do a null check to confirm that we have not already instantiated the
// map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.homemap)).getMap();
LatLng coordinate = new LatLng(lati, longi);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(
coordinate, 15);
mMap.animateCamera(yourLocation);
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(
com.google.android.gms.maps.model.Marker marker) {
marker.showInfoWindow();
return true;
}
});
} else
Toast.makeText(getActivity().getApplicationContext(),
"Unable to create Maps", Toast.LENGTH_SHORT).show();
}
}
public class MarkerInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {
public MarkerInfoWindowAdapter() {
}
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View v = getActivity().getLayoutInflater().inflate(
R.layout.infowindow_layout, null);
MyMarker myMarker = mMarkersHashMap.get(marker);
ImageView markerIcon = (ImageView) v.findViewById(R.id.marker_icon);
TextView markerLabel = (TextView) v.findViewById(R.id.marker_label);
markerIcon.setImageResource(manageMarkerIcon(myMarker.getmIcon()));
markerLabel.setText(myMarker.getmLabel());
TextView anotherLabel = (TextView) v
.findViewById(R.id.another_label);
// anotherLabel.setText("A custom text");
return v;
}
}
private int manageMarkerIcon(String markerIcon) {
if (markerIcon.equalsIgnoreCase("3"))
return R.drawable.ambulance;
else if (markerIcon.equalsIgnoreCase("4"))
return R.drawable.doctor;
else if (markerIcon.equalsIgnoreCase("me"))
return R.drawable.marker;
else
return R.drawable.marker;
}
}
I am attaching my logcat error snap below
this is xml code.
<?xml version="1.0" encoding="utf-8"?>
<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"
android:padding="16dp"
tools:context=".Googlemap.Googlemap">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"/>
</RelativeLayout>
and code should be something like this
private GoogleMap googleMap;
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
googleMap.setMyLocationEnabled(true);
}
hopefully this will work.
I searched a lot and now I found solutions of my problem.
I write below code in my activity.
#Override
public void onDestroyView() {
try {
MapFragment f = (MapFragment) getFragmentManager()
.findFragmentById(R.id.homemap);
if (getActivity().isFinishing()) {
}
else if (f != null)
getActivity().getFragmentManager().beginTransaction().remove(f)
.commit();
} catch (Exception e) {
}
super.onDestroyView();
}
Thanks All for giving you valuable time and suggestions.
I am created a map and it displayed in fragment in another activity .In my application has only one Activity class.I need to display it in Fragment .
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapAtm"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
public class Atm extends Fragment {
private SupportMapFragment mSupportMapFragment;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.atm_main,
container, false);
mSupportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapAtm);
if (mSupportMapFragment == null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
mSupportMapFragment = SupportMapFragment.newInstance();
fragmentTransaction.replace(R.id.mapAtm, mSupportMapFragment).commit();
}
if (mSupportMapFragment != null) {
mSupportMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
if (googleMap != null) {
googleMap.getUiSettings().setAllGesturesEnabled(true);
LatLng marker_latlng = new LatLng(150, -150);
CameraPosition cameraPosition = new CameraPosition.Builder().target(marker_latlng).zoom(15.0f).build();
CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
googleMap.moveCamera(cameraUpdate);
}
}
});
}
return view;
}
}
Their is no error in Emulator.But after installing in Mobile;application will terminate when clicking in Atm Map
Good night,
I have an application with a map in a swipe tab, but I want that map select a point and start at that point.
Thank you in advance.
Enclose JAVA:
public class Mapa extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View android = inflater.inflate(R.layout.mapa_3, container, false);
return android;
}
#Override
public void onDestroyView() {
super.onDestroyView();
Fragment f = getFragmentManager().findFragmentById(R.id.mapFragment);
if (f != null)
getFragmentManager().beginTransaction().remove(f).commit();
}
}
the layout:
<?xml version="1.0" encoding="utf-8"?>
<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"
android:id="#+id/map_container"
tools:context=".Mapa" >
<fragment
android:id="#+id/mapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
I guess you want to add a marker to a map and set camera to look at it. Here is how you can achieve it(more info here and here):
GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View android = inflater.inflate(R.layout.mapa_3, container, false);
final LatLng position = new LatLng(MARKER_LATITUDE, MARKER_LONGITUDE);
// marker
map = ((MapFragment) getSupportFragmentManager().findFragmentById(R.id.mapFragment)).getMap();
map.addMarker(new MarkerOptions()
.position(position)
.title("Hello world"));
// camera position
map.setOnCameraChangeListener(new OnCameraChangeListener()
{
#Override
public void onCameraChange(CameraPosition arg0)
{
CameraUpdate cu = CameraUpdateFactory.newLatLngZoom(position, 14);
map.animateCamera(cu);
map.setOnCameraChangeListener(null);
}
});
return android;
}