Google Map won't display markers - android

Started working with Android Studio, trying to display a Google Map in a fragment. The maps displays fine and I'm able to zoom/move the map around, but my markers will not display.
Here is my MapsActivity (HomePageMapsActivity.java):
public class HomePageMapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page_maps);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so, and the map has not already been instantiated.
* If not installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will prompt user to
* install/update the Google Play services APK on their device.
*/
private void setUpMapIfNeeded() {
// 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 = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers, lines, listeners, or move the camera.
* Only call once and when sure {#link #mMap} is not null.
*/
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(33, -84)).title("Atlanta"));
}
}
The xml (activity_home_page_maps.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/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
tools:context="net.datanetics.campusresponseapp.HomePageMapsActivity" />
The home page xml (activity_home_page):
<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"
android:gravity="center">
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/HomePageMap"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="9"
tools:context=".HomePageMapsActivity"
class="com.google.android.gms.maps.SupportMapFragment" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal"
android:weightSum="1" >
<Button
android:id="#+id/MenuButton"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:background="#3498DB"
android:text="Menu"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/EmergencyButton"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:background="#C1392B"
android:text="Emergency"
android:textColor="#FFFFFF" />
</LinearLayout>

Are you sure, your GoogleMap is not null? Try to get map asynchronously:
public class YourActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
SupportMapFragment fragMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page_maps);
fragMap = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
fragMap.getMapAsync(this);
}
#Override
public void onMapReady(final GoogleMap map) {
if (map != null) {
mMap = map;
setUpMap();
}
}
}

Two things:
1) You are trying to use the map too early. You need to have the view
first, so your code should be in onCreateView() not onCreate().
Correction: onCreateView() applies to fragments, not activities.
The app I used to test this used a Fragment to hold the map, not a
FragmentActivity.
2) I found I needed to prod the initialization of the map layers by
calling mMapView.onCreate() and mMapView.onResume() explicitly. See
also JoelLipman.com.
public class HomePageMaps extends SupportMapFragment {
private View mView;
private View mMapView;
private GoogleMap mMap;
#Override public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle state) {
super.onCreateView(inflater, group, state);
mView = inflater.inflate(R.layout.activity_home_page_maps, group, false);
mMapView= (MapView)mView.findViewById(R.id.map);
mMapView.onCreate(state);
mMapView.onResume();
mMap= mMapView.getMap();
mapUpdate();
return (mView);
}
private void mapUpdate() {
LatLng myLoc= new LatLng(33,-84);
MarkerOptions opt = new MarkerOptions();
mMap.clear();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLoc, 15));
mMap.addMarker(opt.position(myLoc).title("Me"));
}
}

I got your issue change this line
mMap.addMarker(new MarkerOptions().position(new LatLng(33, -84)).title("Atlanta"));
to
mMap.addMarker(new MarkerOptions().position(new LatLng(33.7550,84.3900)).title("Atlanta"));
you have to pass the double value in lat and lng.

I found my "FirstMap" project, hope it helps. You will want to
move your map into a fragment sooner rather than later.
MapsActivity.java
public class MapsActivity extends FragmentActivity {
private PageMap mPageMap;
public interface IAction {
boolean onClick(int BtnID);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageMap= new PageMap();
setContentView(R.layout.activity_main);
}
public void onClick(View Ctrl) {
int BtnID= Ctrl.getId();
switch(BtnID) {
case R.id.MainBtn_Map: ShowMap(); break;
default: mPageMap.onClick(BtnID);
}
}
private void ShowMap() {
LoadPage(mPageMap);
}
public void LoadPage(Fragment NewPage) {
FragmentManager Mgr= getSupportFragmentManager();
FragmentTransaction Action= Mgr.beginTransaction();
Action.replace(R.id.Main_FragmentContainer,NewPage);
Action.show(NewPage);
Action.commit();
}
}
res/layout/activity_main.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"
>
<Button
android:id="#+id/MainBtn_Map"
android:onClick="onClick"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="Load Map"
/>
<LinearLayout
android:id="#+id/Main_FragmentContainer"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#color/material_blue_grey_800"
>
</LinearLayout>
</LinearLayout>
PageMap.java
public class PageMap extends SupportMapFragment implements MapsActivity.IAction {
private FragmentActivity mActivity;
private MapView mMapView;
private GoogleMap mMap;
#Override public void onAttach(Activity parent) {
mActivity= (FragmentActivity)parent;
super.onAttach(parent);
}
#Override public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle instance) {
super.onCreateView(inflater,group,instance);
View view= inflater.inflate(R.layout.page_map,group,false);
mMapView= (MapView)view.findViewById(R.id.map);
mMapView.onCreate(instance);
mMapView.onResume();
mMap= mMapView.getMap();
return(view);
}
public boolean onClick(int BtnID) {
switch(BtnID) {
case R.id.PageMap_BtnUpdate: return (Update());
}
return (false);
}
private boolean Update() {
setUpMap();
return(true);
}
private void setUpMap() {
if(mMap!=null) {
LatLng loc = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(loc).title("Marker"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15));
}
}
}
//EOF: PAGEMAP.JAVA
res/layout/page_map.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<Button
android:id="#+id/PageMap_BtnUpdate"
android:onClick="onClick"
android:text="Update"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<com.google.android.gms.maps.MapView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
/>
</LinearLayout>

Related

MapView is not shown correctly

I am using MapView inside a RecycleView in android.
here is my xml code:
<com.google.android.gms.maps.MapView
android:id="#+id/map_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
and:
private fun initializeMap() {
val mapView : MapView = binding.root.findViewById(R.id.map_view)
mapView?.let {
mapView.onCreate(null)
mapView.getMapAsync(this)
}
}
override fun onMapReady(map: GoogleMap?) {
MapsInitializer.initialize(fragment.context)
googleMap = map
googleMap?.let {
it.setOnMapLoadedCallback { this }
it.setOnMapClickListener { this }
it.uiSettings.setAllGesturesEnabled(false)
it.uiSettings.isZoomControlsEnabled = false
}
}
override fun onMapLoaded() {
}
override fun onMapClick(p0: LatLng?) {
}
the map that appear is like following
and it takes a lot of time tp appear and also does not appear direct, I scroll a lot
also the methods onMapLoaded() and onMapClick() does not call
As you set it.uiSettings.setAllGesturesEnabled(false) and it.uiSettings.isZoomControlsEnabled = false use MapView in Lite Mode:
<com.google.android.gms.maps.MapView
android:id="#+id/map_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
map:cameraZoom="<ZOOM>"
map:mapType="normal"
map:liteMode="true">
Here you can find Official example of using MapView inside RecyclerView and here MapView layout settings:
<!-- MapView in lite mode. Note that it needs to be initialised
programmatically before it can be used. -->
<com.google.android.gms.maps.MapView
android:id="#+id/lite_listrow_map"
android:layout_width="match_parent"
android:layout_height="150dp"
map:liteMode="true" map:mapType="none" />
this my map.xml file
<com.google.android.gms.maps.MapView android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android" />
And this is java class
public class map extends Fragment implements OnMapReadyCallback {
GoogleMap mMap;
private MapView mapView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.map,null);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng ahmedabad = new LatLng(23.022505, 72.571365);
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.icons8fiat50060);
MarkerOptions markerOptions = new MarkerOptions().position(ahmedabad)
.title("Current Location")
.snippet("Thinking of finding some thing...")
.icon(icon);
googleMap.addMarker(markerOptions);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ahmedabad,30f));
}
}
this is quite easy i think this will helpful for you.

How to get marker position when drag googleMap in android

In my application i set one image in my layout center of map, and i want when drag googleMap show latLong of this image (marker).
layout code:
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/mainToolbar"
layout="#layout/toolbar_main" />
<fragment
android:id="#+id/mainMap"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/mainToolbar"
tools:context="com.tida.utils.safine.Activities.MainActivity" />
<ImageView
android:id="#+id/location_setter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/ic_location_origin_pin" />
</RelativeLayout>
Java code:
public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private UiSettings mUiSettings;
private CameraUpdate mapCenter, mapZoom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mainMap);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mUiSettings = mMap.getUiSettings();
mUiSettings.setScrollGesturesEnabled(true);
mUiSettings.setZoomGesturesEnabled(true);
mUiSettings.setTiltGesturesEnabled(true);
mUiSettings.setRotateGesturesEnabled(true);
/*Set center of Tehran location*/
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(35.724414, 51.427059), 18.0f));
/*Map listener*/
mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
Log.e("mapDrag", "DragStart : " + marker.getPosition());
}
#Override
public void onMarkerDrag(Marker marker) {
Log.e("mapDrag", "Drag : " + marker.getPosition());
}
#Override
public void onMarkerDragEnd(Marker marker) {
Log.e("mapDrag", "DragEnd : " + marker.getPosition());
}
});
}
}
How can i set my image for marker and get this position ?
marker.getPosition() returns LatLng
you should use:
marker.getPosition().latitude
&
marker.getPosition().longitude
set marker using global variable of marker and call mMarker.setPosition(marker.getPosition());

Error on use of setMyLocationEnabled

Help with my code, please, setMyLocationEnabled(true) gives an error.
The program closes when running, and I can not find the solution :(
MainActivity.java File:
public class MainActivity extends Activity {
Button btnDireccion;
TextView lblDireccion;
public static double lat = 0;
public static double lon = 0;
public static boolean checked = false; //Se ha chequeado el mapa.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
btnDireccion = (Button)findViewById(R.id.btnDireccion);
lblDireccion = (TextView)findViewById(R.id.lblDireccion);
}
public void mostrarMapa(View view){
Intent pantalla = new Intent(this, SeleccionarDireccion.class);
startActivity(pantalla);
}}
SeleccionarDireccion.java
public class SeleccionarDireccion extends AppCompatActivity {
private LatLng latlong = new LatLng (-6.760644,-79.863413);
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seleccionar_direccion);
MapFragment fMap = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
map.setMyLocationEnabled(true);
map = fMap.getMap();
map.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
public void onMapLongClick(LatLng LL) {
MainActivity.lat = LL.latitude;
MainActivity.lon = LL.longitude;
regresar();
}
});
MainActivity.checked = true;
if (map!=null){
iniciarGPS();
}
}
private void iniciarGPS(){
map.addMarker(new MarkerOptions().position(latlong)
.title("Ubicacion actual"));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latlong,15));
}
public void regresar() {
Intent intent = new Intent(this, MainActivity.class);
intent .setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
this.finish();
} }
activity_seleccionar_direccion.xml
<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"
tools:context="com.androidmorefast.moden.appcapturardireccion.SeleccionarDireccion"
android:name="com.google.android.gms.maps.MapFragment" />
Activity_main.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.androidmorefast.moden.appcapturardireccion.MainActivity">
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="150dp"
android:orientation="vertical" >
<Button
android:id="#+id/btnDireccion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Dirección"
android:onClick="mostrarMapa" />
<TextView
android:id="#+id/lblDireccion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text=" "
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
The getMap method is deprecated and in your case is returning null, so the line map.setMyLocationEnabled(true); is throwing NullPointerException. You should use getMapAsync:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
MapFragment fMap = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
fmap.getMapAsync(this);
}
#Override
public void onMapReady(final GoogleMap googleMap) {
map = googleMap;
map.setMyLocationEnabled(true);
map.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
public void onMapLongClick(LatLng LL) {
MainActivity.lat = LL.latitude;
MainActivity.lon = LL.longitude;
regresar();
}
});
iniciarGPS();
}
}

GoogleMaps.oncameraChangedListener is never called

I have an Activity (which inflates a map fragment) which implements the GoogleMap.onCameraChangedListener, and I have overriden the onCameraChange method.
The problem is that whenever I move across the map, i.e. the camera position changes, the onCameraChange method is never called.
What could be causing this?
Try this :
public class MapActivity extends AppCompatActivity implements
GoogleMap.OnCameraChangeListener{
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.googlemap_layout);
setUpMapIfNeeded();
}
#Override
public void onCameraChange(CameraPosition cameraPosition) {
double latitude = cameraPosition.target.latitude;
double longitude = cameraPosition.target.longitude;
}
private void setUpMapIfNeeded() {
if (googleMap == null) {
// Try to obtain the map from the SupportMapFragment.
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if (googleMap != null) {
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(false);
googleMap.getUiSettings().setZoomControlsEnabled(false);
googleMap.setOnCameraChangeListener(this);
}
}
}
}
Layout :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>

How to use google Map Api2 along-with-other-fragments-in-an-app

Am trying to create and app with one activity but multiple fragment. i am using android.support.v4.* to build the fragment.
Each item i have created so far by extending Fragment, I want to use the google Map Api2 in my application,
All the tutoril i found so far adding the "SupportMapFragment" as an element to layout file.
"<fragment
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>"
But i cannot use this way because nested fragment not supporting, how can i use the google map api2 as a fragment in my application
use the mapview as suggested in Comments
public class InteractiveMapsWidget extends Fragment {
private MapView mMapView;
private GoogleMap mMap;
public void onCreate(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i(TAG, "ON CREATED");
Activity activity = getActivity();
if (activity != null) {
Bundle bundle = getArguments();
`
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i(TAG, "onCreateView");
new DataWorkerAsyncTask(getActivity()).execute(widgetId);
mMapView = (MapView) view.findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
setUpMapIfNeeded();
return view;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((MapView) view.findViewById(R.id.map)).getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
#Override
public void onPause() {
mMapView.onPause();
super.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
}
Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/root_container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>

Categories

Resources