GoogleMap object is null - android

I am trying to add marker on map. But initializeMap() return null.
What could be the issue?
ActivityPlace.java
public class ActivityPlace extends AppCompatActivity {
GoogleMap mMap;
LatLng latlng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place);
if (initializeMap() && checkServices()) {
latlng = new LatLng(latitude, longitude);
MarkerOptions options = new MarkerOptions().position(latlng);
Marker marker = mMap.addMarker(options);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latlng, 12);
mMap.animateCamera(update);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
//Launch Map Page
}
});
}
}
/*
Method to check Google services before initiating map
*/
public boolean checkServices() {
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS){
return true;
}else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)){
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, ERROR_DIALOG_REQUEST);
dialog.show();
}else {
Toast.makeText(this, "Cant connect to mapping service", Toast.LENGTH_SHORT).show();
}
return false;
}
/*
Initialize the map and get a handle to the map to set its location
*/
private boolean initializeMap() {
if (mMap == null) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_fragment);
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
});
}
return (mMap != null);
}
}
activity_place.xml
<?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">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/place_layout">
<TextView
style="#style/txtPrimaryHeading"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:id="#+id/place_name"/>
<include
android:id="#+id/map"
layout="#layout/activity_map_embedded_fragment"
android:layout_width="match_parent"
android:layout_height="200dp" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
activity_map_embedded_fragment.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:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map_fragment"
android:name="com.google.android.gms.maps.SupportMapFragment"
map:uiRotateGestures="false"
map:uiTiltGestures="false"
map:uiScrollGestures="false"
map:uiZoomGestures="false"
map:cameraZoom="12"
map:cameraTargetLat="-35"
map:cameraTargetLng="150"
/>

getMapAsync is async call which will be running in background and your method will return value false only.
My suggestion is to perform other operations when onMapReady is called.
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
latlng = new LatLng(latitude, longitude);
MarkerOptions options = new MarkerOptions().position(latlng);
Marker marker = mMap.addMarker(options);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latlng, 12);
mMap.animateCamera(update);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
//Launch Map Page
}
});
}
});

call this before intitializing map .
GoogleApiClient mGoogleApiClient ;
synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}

Try this. It really works.
GoogleApiClient mGoogleApiClient ;
synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}

Related

Google maps v2 not initializing in fragment

I want to show my current location using Google maps v2 from a fragment however the Google maps is not initializing on start up. When i run the application, it is nor crashing but the map is not showing my current location neither is it displaying anything. I have used this code on my activity and it is fully functional.
Below is my java code:
public class MapFragment extends Fragment implements LocationListener,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,OnMapReadyCallback {
SupportMapFragment mSupportMapFragment;
MapView mMapView;
Location mLastLocation;
Marker mCurrLocationMarker;
private MarkerOptions markerOptions;
protected GoogleApiClient mGoogleApiClient;
private LatLng latLng;
public GoogleMap mMap;
private Marker marker;
LocationRequest mLocationRequest;
private GoogleMap googleMap;
private TextView lastTrip, lastDeliveryText, lastDelivery, lastAmountText, lastAmount, kes,
todayTotal, totalDeliveryText, totalDelivery, totalAmount, totalAmountText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
buildGoogleApiClient();
// inflat and return the layout
View v = inflater.inflate(R.layout.map_fragment, container,
false);
mSupportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapwhere);
if (mSupportMapFragment == null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
mSupportMapFragment = SupportMapFragment.newInstance();
fragmentTransaction.replace(R.id.mapwhere, mSupportMapFragment).commit();
}
if (mSupportMapFragment != null) {
mSupportMapFragment.getMapAsync(this);
}
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Log.d("one","one");
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//mMap.getUiSettings().setZoomControlsEnabled(true);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
Log.d("two","two");
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
Log.d("three","three");
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
Log.d("four","four");
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
Log.d("five","five");
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//mMap.getUiSettings().setZoomControlsEnabled(true);
final Double lat = location.getLatitude();
final Double lng = location.getLongitude();
Log.d("LATLANGz", lat + "|" + lng);
latLng = new LatLng(lat, lng);
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Positionn");
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(false);
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.user_location));
marker = mMap.addMarker(markerOptions);
//move map camera_main
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
#Override
public void onResume() {
super.onResume();
Log.d("hey2","hey2");
// mMapView.onResume();
mSupportMapFragment.onResume();
}
#Override
public void onPause() {
super.onPause();
Log.d("hey1","hey1");
// mMapView.onPause();
mSupportMapFragment.onPause();
}
/* #Override
public void onDestroy() {
super.onDestroy();
// mMapView.onDestroy();
mSupportMapFragment.onDestroy();
}*/
#Override
public void onLowMemory() {
super.onLowMemory();
// mMapView.onLowMemory();
mSupportMapFragment.onLowMemory();
}
#Override
public void onDetach() {
Log.d("detach", "detach");
super.onDetach();
mSupportMapFragment.onDetach();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d("six","six");
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (mGoogleApiClient.isConnected()){
Log.d("seven","six");
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
first of all Chaeck permission in manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
then check method for current location
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
marker = map.addMarker(new MarkerOptions().position(loc));
if(map != null){
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
}
};
then use
mMap.setOnMyLocationChangeListener(myLocationChangeListener);
and be patience map take laoding time depend on you network speed
comment if any query
First check your permissions and your google api key in your manifest
Your xml layout must be something like this without any thing else:
. <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="com.isg_biz.isg_tracking.MainActivity" />
You have to implement OnMapReadyCallback, then
your code should be something like this in onCreate() :
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Do not to copy and past the same xml code literally you have to change (tools : .....) to same that exist in your xml
for documentation, java code & more Please read :
https://developers.google.com/maps/documentation/android-api/map-with-marker

Android Runtime permission don't accept ok, only deny

After fixing another connected problem, now i have this one: i can't click on 'Ok' in the dialog to handle location permission, only on deny.
If i granted permission in manual way (via settings) i have this in log:
W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found.
but i created the key and obtained the json file.
This is my simple activity:
package com.marcocreation.***********;
import *;
public class Maps extends AppCompatActivity implements OnClickListener, OnMapReadyCallback, ActivityCompat.OnRequestPermissionsResultCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleMap mMap;
private Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private static final int REQUEST_LOCATION = 1503;
private double latitude, longitude;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
private boolean mPermissionDenied = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(this);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
Log.i("inside","callback");
switch (requestCode) {
case REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
Log.i("permission", "done");
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
#TargetApi(Build.VERSION_CODES.M)
private void updateMaps(){
String locationPermission = Manifest.permission.ACCESS_FINE_LOCATION;
int hasPermission = ContextCompat.checkSelfPermission(this,locationPermission);
String[] permissions = new String[] { locationPermission };
if (hasPermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions(permissions, REQUEST_LOCATION);
}
else {
// Phew - we already have permission!
mMap.setMyLocationEnabled(true);
Log.i("clicked", "here");
// Access to the location has been granted to the app.
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
Log.i("latitude", "" + latitude);
Log.i("longitude", "" + longitude);
LatLng sydney = new LatLng(latitude, longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
Log.i("latitude", "" + latitude);
Log.i("longitude", "" + longitude);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.i("Connection", "OK");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.i("Connection", "FAILED");
}
}
Activity Layout:
<android.support.design.widget.CoordinatorLayout
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"
android:fitsSystemWindows="true"
tools:context="com.marcocreation.******.Maps">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_maps" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
Included activity:
<RelativeLayout 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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.marcocreation.******.Maps"
tools:showIn="#layout/activity_maps">
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.marcocreation.******.createMatch" />
</RelativeLayout>
Sorry if i wrote stupid things, it's three days i'm going crazy with maps and i edited the code a lot of time.My idea is when i click on the right/down button camera will moves on the user position.
I tried also this lib:
https://github.com/googlemaps/android-samples/blob/master/ApiDemos/app/src/main/java/com/example/mapdemo/PermissionUtils.java
but nothing is changed

How to get the gps co-ordinates from the center of the map in android on moving the map realtime

What i am having:
I have a image that shows on the center of map
What i am trying to do:
When i move the map i want to pick the lat/long co-ordinates from the center of the map and show it in a toast that always changes when i move the map
MainActivity.java
public class MainActivity extends Activity {
ImageView imageView1;
// Google Map
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView1=(ImageView) findViewById(R.id.imageView1);
// Loading map
initilizeMap();
addMarker();
setCamera();
}
private void setCamera() {
//Fix the camera to the user location
MarkerOptions marker = new MarkerOptions().position(new LatLng(12.952782, 77.636247)).title("Your Location");
// HUE_RED color icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(12.952782, 77.636247)).zoom(16).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
private void addMarker() {
MarkerOptions marker = new MarkerOptions().position(new LatLng(12.952782, 77.636247));
// HUE_AZURE color icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
// adding marker
googleMap.addMarker(marker);
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
/**
* function to load map. If map is not created it will create it for you
* #throws Exception
* */
private void initilizeMap() {
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
//Map Explicit settings//
//Map Rotate Gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
//My Location Button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
//Compass Functionality
googleMap.getUiSettings().setCompassEnabled(true);
//Zooming Functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
//Zooming Buttons
googleMap.getUiSettings().setZoomControlsEnabled(true);
//Showing Current Location
googleMap.setMyLocationEnabled(true);
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(this,"Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
}
}
}
activity_main.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"
android:gravity="center" >
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="center" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#drawable/marker" />
</FrameLayout>
edit
googleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
LatLng latLng=googleMap.getCameraPosition().target;
Log.d("TAG", latLng.toString());
//Toast.makeText(this, latLng.toString(), Toast.LENGTH_LONG).show();
}
});
}
});
first of all:-
mMap.getCameraPosition().target
above snipped code will give you center position of Google Map.
at the time of loading map do
googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
Log.e("TAG", googleMap.getCameraPosition().target.toString());
}
});
for when map move:-
googleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
LatLng latLng= arg0.target;
Log.d("TAG", latLng.toString());
//Toast.makeText(this, latLng.toString(), Toast.LENGTH_LONG).show();
}
});
}
});
I hope it will helps you..!

How to get Google Maps object inside a Fragment

I am using fragments in my application and I am new for this. There is a fragment in which I want to display Google Map and want to get its object, for this I have a fragment in my XML and I want to inflate it in the Fragment itself. When I am trying to inflate the map view its showing me error for getSupportFragmentManager().
How do I get the map object then that is the main issue. My XML is like this :-
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="250dp"
class="com.google.android.gms.maps.SupportMapFragment" />
And my Fragment in which I want to get the Google Map object is like that :-
public class FindMyCar extends Fragment {
private TextView mTvFind;
private TextView mTvPark;
private EditText mEtParkHint;
private GoogleMap map;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.findmycar, null);
initViews(view);
Typeface type = Typeface.createFromAsset(getActivity().getResources().getAssets(),"Multicolore.otf");
mTvFind.setTypeface(type);
mTvPark.setTypeface(type);
mEtParkHint.setTypeface(type);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
return view;
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void initViews(View view){
mTvPark = (TextView) view.findViewById(R.id.tvFindCarPark);
mTvFind = (TextView) view.findViewById(R.id.tvFindCar);
mEtParkHint = (EditText) view.findViewById(R.id.etParkHint);
}
Can someone help me to get the object for my map so that I can show current location and draw the marker there.
Any help would be appreciable.
Thanks in advance.
getMap() method is deprecated
getMap() method is deprecated but after the play-services 9.2it is removed, so better use getMapAsync(). You can still use getMap() only if you are not willing to update the play-services 9.2 for your app.
To use getMapAsync(), implement the OnMapReadyCallback interface on your activity or fragment:
For fragment:
public class MapFragment extends android.support.v4.app.Fragment
implements OnMapReadyCallback { /* ... */ }
Then, while initializing the map, use getMapAsync() instead of getMap():
//call this method in your onCreateMethod
private void initializeMap() {
if (mMap == null) {
SupportMapFragment mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.fragment_map);
mapFrag.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setUpMap();// do your map stuff here
}
For Activity:
public class MapActivity extends FragmentActivity
implements OnMapReadyCallback { }
Then, while initializing the map, use getMapAsync() instead of getMap():
//call this method in your onCreateMethod
private void initializeMap() {
if (mMap == null) {
SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_map);
mapFrag.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setUpMap();// do your map stuff here
}
Fragment in XML:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
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"/>
Try this
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" />
Try this it works for me
How to put Google Maps V2 on a Fragment Using ViewPager
<Fragment
android:id="#+id/map"
android:layout_width="wrap_content"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
GoogleMap mGoogleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMap();
Try this i have made this as a sample according to your need
public class LocationMapActivity extends FragmentActivity {
private GoogleMap mMap;
static boolean Iscamera = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.locatio_map);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true);
if (mMap != null) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getMaxZoomLevel();
mMap.getMinZoomLevel();
mMap.getUiSettings();
mMap.animateCamera(CameraUpdateFactory.zoomIn());
mMap.animateCamera(CameraUpdateFactory.zoomOut());
mMap.animateCamera(CameraUpdateFactory.zoomTo(20));
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
mMap.clear();
mMap.addMarker(new MarkerOptions()
.position(
new LatLng(arg0.getLatitude(), arg0
.getLongitude()))
.title("I am Here!!")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.map_icon)));
if (!Iscamera) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(arg0.getLatitude(), arg0
.getLongitude()), 14));
Iscamera = true;
}
try {
if (Constant.FORTNAME.equals("Arad Fort")) {
mMap.addMarker(new MarkerOptions()
.position(new LatLng(26.2525, 50.6269))
.title(Constant.FORTNAME)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.greenicon)));
} else if (Constant.FORTNAME.equals("Bahrain Fort")) {
mMap.addMarker(new MarkerOptions()
.position(
new LatLng(26.2333598,
50.52035139))
.title(Constant.FORTNAME)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.greenicon)));
} else if (Constant.FORTNAME
.equals("International Circuit")) {
mMap.addMarker(new MarkerOptions()
.position(
new LatLng(26.0303251,
50.51121409))
.title(Constant.FORTNAME)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.greenicon)));
} else if (Constant.FORTNAME
.equals("Khamis Mousque")) {
mMap.addMarker(new MarkerOptions()
.position(
new LatLng(26.158719, 50.516426))
.title(Constant.FORTNAME)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.greenicon)));
} else if (Constant.FORTNAME
.equals("king fahad causeway")) {
mMap.addMarker(new MarkerOptions()
.position(
new LatLng(26.1723987,
50.4579942))
.title(Constant.FORTNAME)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.greenicon)));
} else if (Constant.FORTNAME.equals("Riffa Fort")) {
mMap.addMarker(new MarkerOptions()
.position(
new LatLng(26.11771965026855,
50.56298065185547))
.title(Constant.FORTNAME)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.greenicon)));
} else if (Constant.FORTNAME
.equals("Royal Golf Club")) {
mMap.addMarker(new MarkerOptions()
.position(
new LatLng(26.13000, 50.55500))
.title(Constant.FORTNAME)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.greenicon)));
} else if (Constant.FORTNAME.equals("Tree of life")) {
mMap.addMarker(new MarkerOptions()
.position(
new LatLng(25.9940396,
50.583135500000026))
.title(Constant.FORTNAME)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.greenicon)));
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
e.getMessage(), Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
});
}
}
}
// ********************************************************************************************
#SuppressWarnings("unused")
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title(
"Marker"));
}
}
public class MapActivity extends FragmentActivity
implements OnMapReadyCallback { }
Then, while initializing the map, use getMapAsync() instead of getMap():
//call this method in your onCreateMethod
private void initializeMap() {
if (mMap == null) {
SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_map);
mapFrag.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
You can use this to making map but it will return map object is null because you don't find solution with getMapAsync to create a new object mMap. It only background task with return null
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/location_map"
android:layout_above="#id/atmLocation_recyclerView"
/>
View root= inflater.inflate(R.layout.fragment_a_t_m_locations, container, false);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.location_map);
mapFragment.getMapAsync(googleMap -> {
mMap=googleMap;
if(mMap!=null){
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
});
Revised code:
Your xml file-
<fragment
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Your java file (only relevant code)-
View view = null, mapView = null;
private GoogleMap mMap;
view = inflater.inflate(R.layout.findmycar, container,false);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
SupportMapFragment supportMapFragment = (SupportMapFragment) fragmentManager
.findFragmentById(R.id.map);
mMap = supportMapFragment.getMap();
mapView = (View) view.findViewById(R.id.map);

Add Google Maps API V2 in a fragment

I'm trying to show the map from the Google Maps API V2 in fragment. I tried with the SupportMapFragment, but I can't get the expected output.
Also I'm a beginner on this platform! What I really want is just a way to put a map from the Google Maps API V2 for Android in a fragment. Please share your ideas and references.
Thanks in Advance !
Here is the code,
public class YourFragment extends Fragment {
// ...
static final LatLng HAMBURG = new LatLng(53.558, 9.927);
static final LatLng KIEL = new LatLng(53.551, 9.993);
private GoogleMap map;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.yourlayout, null, false);
map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG)
.title("Hamburg"));
Marker kiel = map.addMarker(new MarkerOptions()
.position(KIEL)
.title("Kiel")
.snippet("Kiel is cool")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
//...
return v;
}
Your layout,
<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=".MainActivity" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
Make some changes in your manifest file also.Like,
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myapp.android.locationapi.maps"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="17" />
<permission
android:name="com.myapp.android.locationapi.maps.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="com.myapp.android.locationapi.maps.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.myapp.android.locationapi.maps.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="your_apikey" />
</application>
</manifest>
public class DemoFragment extends Fragment {
MapView mapView;
GoogleMap map;
LatLng CENTER = null;
public LocationManager locationManager;
double longitudeDouble;
double latitudeDouble;
String snippet;
String title;
Location location;
String myAddress;
String LocationId;
String CityName;
String imageURL;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater
.inflate(R.layout.fragment_layout, container, false);
mapView = (MapView) view.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
setMapView();
}
private void setMapView() {
try {
MapsInitializer.initialize(getActivity());
switch (GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getActivity())) {
case ConnectionResult.SUCCESS:
// Toast.makeText(getActivity(), "SUCCESS", Toast.LENGTH_SHORT)
// .show();
// Gets to GoogleMap from the MapView and does initialization
// stuff
if (mapView != null) {
locationManager = ((LocationManager) getActivity()
.getSystemService(Context.LOCATION_SERVICE));
Boolean localBoolean = Boolean.valueOf(locationManager
.isProviderEnabled("network"));
if (localBoolean.booleanValue()) {
CENTER = new LatLng(latitude, longitude);
} else {
}
map = mapView.getMap();
if (map == null) {
Log.d("", "Map Fragment Not Found or no Map in it!!");
}
map.clear();
try {
map.addMarker(new MarkerOptions().position(CENTER)
.title(CityName).snippet(""));
} catch (Exception e) {
e.printStackTrace();
}
map.setIndoorEnabled(true);
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.zoomTo(5));
if (CENTER != null) {
map.animateCamera(
CameraUpdateFactory.newLatLng(CENTER), 1750,
null);
}
// add circle
CircleOptions circle = new CircleOptions();
circle.center(CENTER).fillColor(Color.BLUE).radius(10);
map.addCircle(circle);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
break;
case ConnectionResult.SERVICE_MISSING:
break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
break;
default:
}
} catch (Exception e) {
}
}
in fragment_layout
<com.google.android.gms.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="160dp"
android:layout_marginRight="10dp" />
Update 10/24/2014 This is all wrong. You shouldn't have a fragment in a fragment. Rather you should extend the SupportMapFragment. See this stackoverflow post for some details: https://stackoverflow.com/a/19815266/568197
here is my onDestroyView()
public void onDestroyView() {
super.onDestroyView();
if (mMap != null) {
getFragmentManager()
.beginTransaction()
.remove(getFragmentManager().findFragmentById(R.id.map))
.commit();
}
}
in addition to the answer above, I also had to put the following lines to my manifest
<!-- inside <aplication> tag -->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
And I also changed the layout to use SupportMapFragment instead of MapFragment
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
Here is my code.
Create project in google map concole and generate api key.
and then add dependency to build.gradle(app level).
compile 'com.google.android.gms:play-services-maps:10.2.1'
compile 'com.google.android.gms:play-services-location:10.2.1'
compile 'com.google.android.gms:play-services-places:10.2.1'
remember to add permissions in Android.manifest
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-feature android:name="android.hardware.location.gps" android:required="true"/>
create activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame">
<fragment
class="com.googlelocationmapdemo.FragmentLocation"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
nothing to call from MainActivity.class
Create fragment_location.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearMap"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Create FragmentLocation.class
public class FragmentLocation extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
public static final String TAG = FragmentLocation.class.getSimpleName();
public static final int REQUEST_CODE_FOR_PERMISSIONS = 1;
GoogleApiClient mGoogleApiClient;
LatLng mLatLng;
GoogleMap mGoogleMap;
Marker mCurrLocationMarker;
private LinearLayout linearMap;
Location mLastLocation;
LocationManager locationManager;
boolean statusOfGPS;
private Dialog mDialogGPS;
View view;
LocationRequest mLocationRequest;
SupportMapFragment mFragment;
FragmentManager fragmentManager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view=inflater.inflate(R.layout.fragment_location,container,false);
fragmentManager=getChildFragmentManager();
mFragment = (SupportMapFragment)fragmentManager.findFragmentById(R.id.map);
mFragment.getMapAsync(this);
if (!isGooglePlayServicesAvailable()) {
Toast.makeText(getActivity(), "play services not available", Toast.LENGTH_SHORT).show();
}
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
return view;
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000); //5 seconds
mLocationRequest.setFastestInterval(2000); //3 seconds
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(mLatLng);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(mLatLng));
// Zoom in the Google Map
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (getActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED &&
getActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION
, Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_FOR_PERMISSIONS);
}
} else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
//show dialog when click on location top-right side located on map.
mGoogleMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!statusOfGPS) {
turnOnGps();
} else {
getCurrentLocation(mLastLocation);
}
return false;
}
});
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show();
return false;
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE_FOR_PERMISSIONS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (getActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED &&
getActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
if (!(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_COARSE_LOCATION)) && (!(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)))) {
Snackbar snackbar = Snackbar.make(linearMap, "Never asked"
, Snackbar.LENGTH_INDEFINITE);
snackbar.setAction("Allow", new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
});
snackbar.show();
}
}
break;
}
}
private void getCurrentLocation(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
if (locationManager != null) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLastLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);//getting last location
}
if (mLastLocation != null) {
if (mGoogleMap != null) {
Log.d("activity", "LOC by Network");
mLatLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(mLatLng);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(mLatLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
}
}
}
private void turnOnGps() {
if (mGoogleMap != null) {
mGoogleMap.clear();
}
statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);//getting status of gps whether gps is on or off.
mDialogGPS = new Dialog(getActivity(), R.style.MyDialogTheme);
mDialogGPS.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialogGPS.setContentView(R.layout.dialog_turnongps);
TextView txtCancel = (TextView) mDialogGPS.findViewById(R.id.txtCancel);
TextView txtOK = (TextView) mDialogGPS.findViewById(R.id.txtSetting);
ImageView imgLocation = (ImageView) mDialogGPS.findViewById(R.id.imgLocation);
imgLocation.setImageResource(R.drawable.ic_location_my);
txtCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDialogGPS.dismiss();
//finish();
if (!statusOfGPS) {
getCurrentLocationByDefault();
} else {
getCurrentLocation(mLastLocation);
}
}
});
txtOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//It is use to redirect to setting->location to turn on gps when press ok.
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
mDialogGPS.dismiss();
if (!statusOfGPS) {
getCurrentLocationByDefault();
} else {
getCurrentLocation(mLastLocation);
}
}
});
mDialogGPS.show();
}
private void getCurrentLocationByDefault() {
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
if (mGoogleMap != null) {
LatLng xFrom1 = new LatLng(0.0, 0.0);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(xFrom1, (float) 0.0));
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(xFrom1);
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_taxi));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
} else {
Log.i("MainActivity", "getCurrentLocationByDefault else");
}
}
#Override
public void onResume() {
super.onResume();
statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (mDialogGPS != null) {
if (mDialogGPS.isShowing()) {
mDialogGPS.dismiss();
}
}
if (!statusOfGPS) {
turnOnGps();
} else {
getCurrentLocation(mLastLocation);
}
}
protected synchronized void buildGoogleApiClient() {
if (mGoogleApiClient != null) {
mGoogleApiClient = null;
}
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
}
create dailog_gps.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/txtPhoneNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Use Location?"
android:textColor="#android:color/black"
android:textSize="16sp"
/>
</LinearLayout>
<LinearLayout
android:layout_marginTop="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="This app wants to change your \ndevice settings:"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:layout_marginTop="10dp"
android:weightSum="2"
android:gravity="center"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imgLocation"
android:layout_weight="1"
android:layout_gravity="top"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Use GPS, Wi-Fi and mobile \nnetwork for location"
android:layout_marginLeft="20dp"
android:textSize="12sp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:orientation="horizontal"
android:layout_marginTop="20dp">
<TextView
android:id="#+id/txtCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NO"
android:layout_marginRight="30dp"
android:textSize="16sp" />
<TextView
android:id="#+id/txtSetting"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="YES"
android:layout_marginRight="30dp"
android:textSize="16sp" />
</LinearLayout>
</LinearLayout>
Hope this will help you :-)
Use SupportMapFragment instead of MapFragment and use getActivity()
This is a basic example using SupportMapFragment:
public class MainActivity extends ActionBarActivity implements OnMapReadyCallback{
private SupportMapFragment map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
map.getMapAsync(this);//remember getMap() is deprecated!
}
#Override
public void onMapReady(GoogleMap map) {
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(47.17, 27.5699), 16));
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(47.17, 27.5699))); //Iasi, Romania
map.setMyLocationEnabled(true);
}
}
and change the reference in your layout:
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
For all those friends who are facing the problem:-
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap com.google.android.gms.maps.SupportMapFragment.getMap()
Please try integrate GoogleMap using code
FragmentManager fm = getChildFragmentManager();
googleMap = ((SupportMapFragment)fm.findFragmentById(R.id.googleMap)).getMap();
I've the same issue , I use this code but I still get this error :
unable to instantiate fragment com.google.android.gsm.SupportMapFragment: make sure class name exists ,is public, and has empty construct or that is public
I solved it from here : How to put Google Maps V2 on a Fragment Using ViewPager
If you are using android studio create google mapsactivity its default map fragment and generate your map API KEY and do your stuff......
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
and our override method
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng map = new LatLng(lat, lon);
mMap.addMarker(new MarkerOptions().position(map).title("your title"));
mMap.animateCamera(CameraUpdateFactory.newLatLng(map));
mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
}
This example was build from the auto generated code from android studio, you dont need to change nothing in maps activity, only the context in the layout file to match your maps Activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<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="300dp"
tools:context="com.gearwell.app.gpsmaps02.Gpsenmapa"
/>
<LinearLayout
android:id="#+id/layButtonH"
android:layout_height="150dp"
android:layout_marginTop="50dp"
android:layout_width="fill_parent"
android:gravity="center"
android:layout_weight="0.15">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Obtener Ubicacion"
android:id="#+id/btnLocation"
android:onClick="onClick"/>
</LinearLayout>
</LinearLayout>
Using MapView within Fragment under Google Maps Android API v2.0
public class MapFragment extends Fragment {
MapView m;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.map_fragment, container, false);
m = (MapView) v.findViewById(R.id.mapView);
m.onCreate(savedInstanceState);
return v;
}
#Override
public void onResume() {
super.onResume();
m.onResume();
}
#Override
public void onPause() {
super.onPause();
m.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
m.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
m.onLowMemory();
}
}
http://ucla.jamesyxu.com/?p=287

Categories

Resources