MapView isn't showing android - android

I'm working with Google Maps API For Android.
I'm using a MapView since it's inside a Fragment in a ViewPager.
Unfortunately, it doesn't show as expected.
The compilator give me this error :
[doInBackground] fail to retrieve url: https://play.google.com/store/apps/details?myApp...
Why ? I'm using this in debug environment, it should look for the playstore.
Here is my manifest and my layouts:
<?xml version="1.0" encoding="utf-8"?>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<permission
android:name="faurecia.captordisplayer.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="faurecia.captordisplayer.permission.MAPS_RECEIVE" />
<!-- Permission pour utiliser la connexion internet -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Permission permettant de vérifier l'état de la connexion -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Permission pour stocker des données en cache de la map -->
<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="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name=".Application">
<uses-library android:name="com.google.android.maps" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyCKYeYG6IDbaRAs-rLmS3W_Zx8q742F5VU"/>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
my activity fragment :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.gms.maps.MapView
android:id="#+id/mapview"
android:layout_width="300px"
android:layout_height="300px"
android:apiKey="AIzaSyCKYeYG6IDbaRAs-rLmS3W_Zx8q742F5VU"/>
<faurecia.captordisplayer.view.GradientGauge
android:id="#+id/gradientGauge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical">
<faurecia.captordisplayer.view.EnginePowerGauge
android:id="#+id/engineGauge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<faurecia.captordisplayer.view.Speedmeter
android:id="#+id/speedmeter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<faurecia.captordisplayer.view.RankingGauge
android:id="#+id/rankingGauge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
and my fragment code :
public class HMI0Fragment extends HMIFragment implements OnMapReadyCallback {
#Bind(R.id.mapview) MapView mMapView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
reScheduleTimerTask(TIMER_PERIOD);
mView = inflater.inflate(R.layout.fragment_hmi0, container, false);
ButterKnife.bind(this, mView);
mMapView.getMapAsync(this);
return mView;
}
#Override
public void onMapReady(GoogleMap map) {
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(-18.142, 178.431), 2));
// Polylines are useful for marking paths and routes on the map.
map.addPolyline(new PolylineOptions().geodesic(true)
.add(new LatLng(-33.866, 151.195)) // Sydney
.add(new LatLng(-18.142, 178.431)) // Fiji
.add(new LatLng(21.291, -157.821)) // Hawaii
.add(new LatLng(37.423, -122.091)) // Mountain View
);
}
}

To use the Google Maps Android API, you must register your app project on the Google Developers Console and get a Google API key which you can add to your app. The type of API key you need is an Android key.
Follow instructions here to set up a maps API key: https://developers.google.com/maps/documentation/android-api/signup#release-cert
Make a project in the Google Developers Console
Generate a key to use the Maps API
Add the key to your android manifest
Just call the onCreate() method before you call getMapAsync() and once the callback is called, you need to call onResume() on the MapView object.
public class MainActivity extends MapActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (getView() != null) {
final MapView mapView = (MapView)getView().findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng coordinates = new LatLng(match.match.LocationLatitude, match.match.LocationLongitude);
googleMap.addMarker(new MarkerOptions().position(coordinates).title(match.match.LocationAddress));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 15));
mapView.onResume();
}
}
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Here's a demo app demonstrate how to use Maps API for Android using SupportMapFragment - getMapAsync: https://github.com/googlemaps/android-samples/tree/master/ApiDemos

Thanks for the explanation but the trouble was elsewhere.
When including a MapView inside a Fragment, you have to override all the fragment state (OnResume, OnPause etc) and use the MapView.
Here is a sample :
public class HMI0Fragment extends HMIFragment implements OnMapReadyCallback {
private static int TIMER_PERIOD = 4000;
private static String NAME = "HMI0";
#Bind(R.id.mapview) MapView mMapView;
private boolean mapsSupported = true;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
MapsInitializer.initialize(getActivity());
if (mMapView != null) {
mMapView.onCreate(savedInstanceState);
}
initializeMap();
}
private void initializeMap() {
if ( mapsSupported) {
mMapView = (MapView) getActivity().findViewById(R.id.mapview);
mMapView.getMapAsync(this);
//setup markers etc...
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
reScheduleTimerTask(TIMER_PERIOD);
mView = inflater.inflate(R.layout.fragment_hmi0, container, false);
ButterKnife.bind(this, mView);
return mView;
}
#Override
public void onMapReady(GoogleMap map) {
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(-18.142, 178.431), 2));
// Polylines are useful for marking paths and routes on the map.
map.addPolyline(new PolylineOptions().geodesic(true)
.add(new LatLng(-33.866, 151.195)) // Sydney
.add(new LatLng(-18.142, 178.431)) // Fiji
.add(new LatLng(21.291, -157.821)) // Hawaii
.add(new LatLng(37.423, -122.091)) // Mountain View
);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
initializeMap();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}

Related

Google map not loading completely in Android fragment (Partial loading issue)

I'm developing an Android application which requires Google maps to be loaded in a fragment.
The map loads only partially. Half of the map remains gray and doesn't load.
Please provide your suggestions. I'm not sure about the issue.
Below are the project files :
MapFragment.java:
public class MapFragment extends Fragment {
MapView mMapView;
GoogleMap googleMap;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.fragment_map, container, false);
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
context = getContext();
DatabaseHelper databaseHelper = new DatabaseHelper(context, null, null, 0);
ArrayList<PropertyDetails> arrayList = databaseHelper.readData();
Log.d("PAVAN", "Details "+arrayList.get(0).getCity());
Log.d("PAVAN", "Details "+arrayList.get(0).getLatitude());
googleMap = mMapView.getMap();
for(int i = 0 ; i < arrayList.size() ; i++) {
// latitude and longitude
String PropertyType = arrayList.get(i).PropertyType;
String Address = arrayList.get(i).Address;
String City = arrayList.get(i).City;
Double LoanAmount = arrayList.get(i).LoanAmount;
Double APR = arrayList.get(i).APR;
Double MonthlyPayment = arrayList.get(i).MonthlyPayment;
Double Latitude = arrayList.get(i).getLatitude();
Double Longitude = arrayList.get(i).getLongitude();
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(Latitude, Longitude)).title(PropertyType + "<br/>" + Address + "<br/>" +
City + '\n' + LoanAmount + '\n' + APR + "<br/>" + MonthlyPayment).snippet("" + APR).snippet("" + MonthlyPayment);
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(17.385044, 78.486671)).zoom(12).build();
// googleMap.setInfoWindowAdapter(CustomWindowAdapter);
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
// Perform any camera updates here
return v;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
fragment_map.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:paddingTop="8dp"
tools:context="com.example.pavanshah.mortgagecalculator.MainActivity$PlaceholderFragment">
<com.google.android.gms.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Manifest File:
<?xml version="1.0" encoding="utf-8"?>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<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.gms.version"
android:value="#integer/google_play_services_version">
</meta-data>
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="My_Key">
</meta-data>
</application>
Screenshots:

Google map app crashes on android OS 4.3

I built an app for map. Added all the necessary permissions and generated the api key but it is still crashing. I am working on command line and implemented it on Android 4.3 OS.
Here is the code:
public class MainActivity extends FragmentActivity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Manifest File
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="17" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<!-- The following two permissions are not required to use
Google Maps Android API v2, but are recommended. -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<permission
android:name="mapdemo.exp.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="mapdemo.exp.permission.MAPS_RECEIVE"/>
<application android:label="#string/app_name" android:icon="#drawable/ic_launcher">
<activity android:name="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="AIzaSyAS08XqNbdRuxsOwNrosza0WE2mijfdoO8"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="4323000" />
</application>
Tried this
public class ActivityMain extends Activity
{
public GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try
{
Log.e("loading map. . . .", "loading map. . . ");
initilizeMap();
}
catch (Exception e)
{
Log.e("catch. . .", "catch. . .");
e.printStackTrace();
}
}
private void initilizeMap()
{
Log.e("initializing map. . . ", "initializing map. . ");
if (googleMap == null)
{
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
if (googleMap == null)
{
Toast.makeText(getApplicationContext(),"Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onResume()
{
super.onResume();
initilizeMap();
}
}
Try This
In xml
<?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"
android:orientation="vertical" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment"
/>
</LinearLayout>
In Activity:-
public class ActivityMain extends Activity {
// Google Map
public GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
Log.e("loading map. . . .", "loading map. . . ");
// Loading map
initilizeMap();
} catch (Exception e) {
Log.e("catch. . .", "catch. . .");
e.printStackTrace();
}
/*
* MapFunctionality mf = new MapFunctionality(); mf.currentLoc();
* mf.addMarker();
*/
}
/**
* function to load map. If map is not created it will create it for you
* */
private void initilizeMap() {
// MapFunctionality mf = new MapFunctionality();
Log.e("initializing map. . . ", "initializing map. . ");
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
// mf.currentLoc();
// mf.addMarker();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
Follow these Link 1 and Link 2
Hope it will help you to sort out with your problem
Good Luck

google map tiles load only after taking an action

I am having a small issue when starting my app. The tiles which should show up are only loaded after tapping on the map... afterwards all seems to work fine!
In logcat I see the following error:
E/EnterpriseContainerManager﹕ ContainerPolicy Service is not yet
ready!!!
public class MainActivity extends FragmentActivity {
private static final String TAG = "MAIN_ACTIVITY";
private MyLocationListener locListener;
private SupportMapFragment supportMapFragment;
private GoogleMap gmap;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setUpMap();
list = new ArrayList<GPSCoordinates>();
new Object();
}
#Override
protected void onStart() {
super.onStart();
if (gmap == null) {
gmap = supportMapFragment.getMap();
Log.i(TAG, "gmap set!");
}
if(locListener == null) {
this.initLocationManager();
}
Log.i(TAG, "gmap start!");
}
#Override
protected void onStop() {
super.onStop();
Log.i(TAG, "gmap stop!");
}
private void setUpMap() {
GoogleMapOptions options = new GoogleMapOptions();
options.mapType(GoogleMap.MAP_TYPE_NORMAL)
.camera(CameraPosition.fromLatLngZoom(new LatLng(47.384906, 15.093149), 25));
//supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
if(supportMapFragment == null) {
supportMapFragment = SupportMapFragment.newInstance(options);
getSupportFragmentManager().beginTransaction().replace(R.id.map, supportMapFragment).commit();
}
}
}
<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="at.ac.unileoben.infotech.paapp.MainActivity"
tools:ignore="MissingPrefix">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.SupportMapFragment" />
</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="at.ac.unileoben.infotech.paapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="at.ac.unileoben.infotech.paapp.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<permission android:name="at.ac.unileoben.infotech.paapp.permission.MAPS_RECEIVE" android:protectionLevel="signature"/>
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="at.ac.unileoben.infotech.paapp.MainActivity"
android:label="#string/app_name"
android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="at.ac.unileoben.infotech.paapp.SettingsActivity"
android:label="#string/action_settings" />
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="XXX" />
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version"/>
</application>
</manifest>
edit:
i changed the code of my main_activity to the following..
public class MainActivity extends FragmentActivity {
private ArrayList<GPSCoordinates> list;
private static final String TAG = "MAIN_ACTIVITY";
private static Context context;
private MyLocationListener locListener;
private SupportMapFragment supportMapFragment;
private GoogleMap gmap;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setUpMap();
list = new ArrayList<GPSCoordinates>();
// access context global
MainActivity.context = getApplicationContext();
new Object();
}
#Override
protected void onStart() {
super.onStart();
if (gmap == null) {
gmap = supportMapFragment.getMap();
Log.i(TAG, "gmap set!");
}
if(locListener == null) {
this.initLocationManager();
}
Log.i(TAG, "gmap start!");
}
#Override
protected void onResume() {
super.onResume();
Log.i(TAG, "gmap resume!");
}
private void setUpMap() {
if(supportMapFragment == null) {
supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
}
}
later on im calling my simulatelocationmanager with:
private void initLocationManager() {
locListener = new MyLocationListener(gmap);
// Define a listener that responds to location updates
// Register the listener with the Location Manager to receive location updates
SimulateLocationManager simulatedLocationManager = new SimulateLocationManager();
//LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
simulatedLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 0, locListener);
Log.i(TAG, "locListener");
}
in the locationmanager i call the function viewlocation onlocationchanged
public void viewLocation(double latitude, double longitude)
{
float bearing = this.bearing();
Log.i(TAG2, "bearing" + bearing);
gmap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder()
.target(new LatLng(latitude, longitude))
.bearing(bearing)
.tilt(55f)
.zoom(gmap.getCameraPosition().zoom).build()));
}
as i allready said before the problem is that the tiles arent shown till i tap on the map..
all the other things seem to work because i can see the camera moving. but why are the tiles not loaded?
thank you for your reply!
Already accepted answer is there about your issue :Find here
If you set up the SupportMapFragment via the <fragment> element in the layout, you can call getMap() successfully in onCreate(). But, if you create the SupportMapFragment via the constructor, that's too soon -- the GoogleMap does not yet exist. You can extend SupportMapFragment and override onActivityCreated(), as getMap() is ready by then.
However, getMap() can also return null for a bigger problem, such as Google Play Services not being installed. You would need to use something like GooglePlayServicesUtil.isGooglePlayServicesAvailable() to detect this condition and deal with it however you wish.

google maps v2 center mylocation

I am having some prolems with my google maps app. For now the app was only suppost to get my location em zoom in it, but is not working. My location aways ends in the top of the map. Here is my code:
MainActivity:
public class MainActivity extends Activity implements LocationListener {
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (isGooglePlayOk()) {
setContentView(R.layout.activity_main);
setMap();
googleMap.setMyLocationEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.action_legalnotices:
startActivity(new Intent(this, LegalNoticeActivity.class));
return true;
default:
return false;
}
}
private boolean isGooglePlayOk() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (status == ConnectionResult.SUCCESS) {
return (true);
}
else {
((Dialog) GooglePlayServicesUtil.getErrorDialog(status, this, 10))
.show();
}
return (false);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.main.map)).getMap();
if (googleMap != null) {
}
googleMap.setMyLocationEnabled(true);
LocationManager la = (LocationManager) getSystemService(LOCATION_SERVICE);
String provider = la.getBestProvider(new Criteria(), true);
Location loc = la.getLastKnownLocation(provider);
if (provider != null) {
onLocationChanged(loc);
}
googleMap.setOnMapLongClickListener(onLongClickMapSettiins());
}
}
private OnMapLongClickListener onLongClickMapSettiins() {
// TODO Auto-generated method stub
return new OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng point) {
Toast.makeText(getApplicationContext(), "OK",
Toast.LENGTH_SHORT).show();
}
};
}
#Override
public void onLocationChanged(Location location) {
LatLng latlong = new LatLng(location.getLatitude(),
location.getLongitude());
googleMap.setMyLocationEnabled(true);
CameraPosition cp = new CameraPosition.Builder().target(latlong)
.zoom(15).build();
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cp));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+main/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"/>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mapateste"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<!--
The following two permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<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" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="(My Api is working fine)" />
<activity
android:name="com.example.mapateste.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>
<activity
android:name="com.example.mapateste.LegalNoticeActivity"
android:label="#string/title_activity_legal_notice" >
</activity>
</application>
I can only test in my device. The map is working fine but i cannot get my position on the center of the screen right away only clicking at the mylocationbutton. Somebody can help me?
Just declare a point where you want to center your point.
LatLng cur_Latlng = new LatLng(21.0000, 78.0000);
gm.moveCamera(CameraUpdateFactory.newLatLng(cur_Latlng));
gm.animateCamera(CameraUpdateFactory.zoomTo(4));
the desired zoom level is in the range of 2.0 to 21.0.
// try this
#Override
public void onLocationChanged(Location location) {
LatLng latlong = new LatLng(location.getLatitude(),
location.getLongitude());
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latlong));
googleMap.animateCamera(CameraUpdateFactory.zoomBy(15));
}
Your min sdk is 8. You should use SupportMapFragment. Your class must extend FragmentActivtiy
Check the line above developers guide heading in the below link
https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/MapFragment
<fragment
class="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Use SupportMapFragment
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
GoogleMap mMap = fm.getMap();
Make sure you have added support library
Also make sure you imported the below
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.SupportMapFragment
To zoom
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latlong,20);
googleMap.moveCamera(update);
This is working Current Location with zoom for Google Map V2
double lat= location.getLatitude();
double lng = location.getLongitude();
LatLng ll = new LatLng(lat, lng);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 20));
Note that the My Location layer does not return any data. If you wish to access location data programmatically, use the Location API.
In your MainActivity (onCreate Method)
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(MainActivity.this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
On method onMapReady
#Override
public void onMapReady(GoogleMap googleMap) {
GoogleMap mMap = googleMap;
// Set blue point on the map at your cuurent location
mMap.setMyLocationEnabled(true);
// Show zoon controls on the map layer
mMap.getUiSettings().setZoomControlsEnabled(true);
//Show My Location Button on the map
mMap.getUiSettings().setMyLocationButtonEnabled(true);
}
on method onConnected
#Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
LocationListener.latlonInit= new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude());
CameraPosition target = CameraPosition.builder().tilt(66.0f).target(LocationListener.latlonInit)
.zoom(MainActivity.ZOOM).build();
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(target));
}
}
You class should extend Fragment Activity
public class MainActivity extends FragmentActivity {
//assign any arbitrary value to GPS_ERRODIALOG_REQUEST
private static final int GPS_ERRORDIALOG_REQUEST = 9001;
GoogleMap googlemap;
}
for Google Service Ok method I would do Following:
public boolean isGooglePlayOk(){
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
}
else if(GooglePlayServicesUtil.isUserRecoverableError(isAvailable)){
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, GPS_ERRORDIALOG_REQUEST);
dialog.show();
}
else {
Toast.makeText(this, "Can't connect to Goolge Play", Toast.LENGTH_SHORT).show();
}
return false;
}
In the .xml file, when you declare the fragment, you need to support Map Fragment since your min skd is 8:
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:maps="http://schemas.android.com/apk/res-auto"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
activity_map.xml is for displaying map if condition is true for setMap else go to you regular activity_main.xml.
public class MainActivity extends FragmentActivity {
GoogleMap mMap;
if (isGooglePlayOk()) {
setContentView(R.layout.activity_map);
if (setMap()) {
mMap.setMyLocationEnabled(true);
}
else {
//your code
}
}
else {
setContentView(R.layout.activity_main);
}
method for setMap:
private boolean setMap() {
if (mMap == null) {
SupportMapFragment mapFrag =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFrag.getMap();
}
return (mMap != null);
}
If you want to automatically zoom to some point in google maps v2 u can do like this
private float previousZoomLevel = 13.00f;
LatLng zoomPoint = new LatLng(12.977286, 77.632720);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(zoomPoint,previousZoomLevel));
here previousZoomLevel is level of zoom

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