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

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:

Related

Current Location in Map fragment Android Studio

I'm new to Android Development and I am trying to development an application which will display a google map with the users current location. I have been sucessful in incorporating the map in and adding markers but having issues with getting the current location. I have added location permissions in.
activity_location.xml
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
Android Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.alicearmstrong.coffeysloyaltyprojectv1">
<uses-permission android:name="android.permission.INTERNET" />
<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.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme.NoActionBar">
<uses-library android:name="org.apache.http.legacy" android:required="false" />
<activity
android:name=".NavigationMainOwner"
android:label="#string/title_activity_navigation_main_owner" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/api_map_key" />
....
LocationFragment.java
public class LocationFragment extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private LocationViewModel locationViewModel;
private GoogleMap gMap;
private MapView mapView;
private Location currentLocation;
private int LOCATION_PERMISSION_REQUEST_CODE = 1234;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
locationViewModel = ViewModelProviders.of( this ).get( LocationViewModel.class );
View view = inflater.inflate( R.layout.fragment_location_customer, container, false );
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated( view, savedInstanceState );
mapView = (MapView) view.findViewById( R.id.map );
if (mapView != null)
{
mapView.onCreate( null );
mapView.onResume();
mapView.getMapAsync( this );
checkLocationPermission();
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
MapsInitializer.initialize( getContext() );
gMap = googleMap;
LatLng coffeys = new LatLng( 54.572720, -5.959151 );
gMap.addMarker( new MarkerOptions().position( coffeys ).title( "Coffey's Butchers" ) );
gMap.moveCamera( CameraUpdateFactory.newLatLngZoom( coffeys, 12 ) );
}
private final LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// GPS may be turned off
if (location == null) {
return;
}
Double lat = location.getLatitude();
Double lng = location.getLongitude();
currentLocation = location;
Toast.makeText( getActivity(), "Updated Location: " + lat + lng, Toast.LENGTH_SHORT ).show();
}
};
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public boolean checkLocationPermission()
{
if (ContextCompat.checkSelfPermission( getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION )
!= PackageManager.PERMISSION_GRANTED)
{
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale( getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION ))
{
//Prompt the user once explanation has been shown
requestPermissions( new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE
);
} else {
// No explanation needed, we can request the permission.
requestPermissions( new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE );
}
return false;
}
else
{
return true;
}
}
}
Any help in the right direction would be greatly appreciated! Many Thanks.
You can use Google Maps default current location setting it with gMap.setmylocationenabled(true). Or you can use moveCamera(CameraUpdate update) when getting your current location in your locationListener.

Search view is not working on map API

I'm using this code, and I'm getting false value in
if(intent.getAction().equals(Intent.ACTION_SEARCH))
this condition, so Search view is not working. Appreciate any help.
MapsActivity
public class MapsActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor>,OnMapReadyCallback {
private GoogleMap mMap;
private PopupMenu supportMenuInflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = fragment.getMap();
Log.e("MAP"," load");
handleIntent(getIntent());
}
private void handleIntent(Intent intent){
Log.e("handle intent"," load"+intent);
Log.e("handle intent"," rate "+intent.getAction().equals(Intent.ACTION_SEARCH));
if(intent.getAction().equals(Intent.ACTION_SEARCH))
{
Log.e("handle intent"," if"+intent.getAction().equals(Intent.ACTION_SEARCH));
doSearch(intent.getStringExtra(SearchManager.QUERY));
}
else if(intent.getAction().equals(Intent.ACTION_VIEW))
{
Log.e("handle intent"," else if");
getPlace(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
}
else
{
Log.e("handle intent"," else");
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
handleIntent(intent);
}
private void doSearch(String query){
Log.e("Dosearch"," load "+query);
Bundle data = new Bundle();
data.putString("query", query);
getSupportLoaderManager().restartLoader(0, data, this);
}
private void getPlace(String query){
Log.e("getPlace"," load "+query);
Bundle data = new Bundle();
data.putString("query", query);
getSupportLoaderManager().restartLoader(1, data, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu
getMenuInflater().inflate(R.menu.main, menu);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView search = (SearchView) menu.findItem(R.id.action_search).getActionView();
search.setIconifiedByDefault(false);
search.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String query) {
doSearch(query);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
});
}
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()){
case R.id.action_search:
onSearchRequested();
break;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle query) {
CursorLoader cLoader = null;
if(arg0==0)
cLoader = new CursorLoader(getBaseContext(), PlaceProvider.SEARCH_URI, null, null, new String[]{ query.getString("query") }, null);
else if(arg0==1)
cLoader = new CursorLoader(getBaseContext(), PlaceProvider.DETAILS_URI, null, null, new String[]{ query.getString("query") }, null);
return cLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor c) {
showLocations(c);
}
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
// TODO Auto-generated method stub
}
private void showLocations(Cursor c){
MarkerOptions markerOptions = null;
LatLng position = null;
mMap.clear();
while(c.moveToNext()){
markerOptions = new MarkerOptions();
position = new LatLng(Double.parseDouble(c.getString(1)),Double.parseDouble(c.getString(2)));
markerOptions.position(position);
markerOptions.title(c.getString(0));
mMap.addMarker(markerOptions);
}
if(position!=null){
CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(position);
mMap.animateCamera(cameraPosition);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
Log.e("OnReady", String.valueOf(sydney));
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
Error Was in Manifest file
enter code here
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<!-- Protect the map component of the application using application signature -->
<permission
android:name="com.example.user.demo.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<!-- Allows to receive map -->
<uses-permission android:name="com.example.user.demo.MAPS_RECEIVE" />
<!-- Used by the Google Maps Android API V2 to download map tiles from Google Maps servers -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Allows the Google Maps Android API V2 to cache map tile data in the device's external storage area -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Allows the Google Maps Android API V2 to use WiFi or mobile cell data (or both) to determine the device's location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- Allows the Google Maps Android API V2 to use the Global Positioning System (GPS)
to determine the device's location to within a very small area -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- Allows to contact Google Serves -->
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!-- Google Maps Android API V2 requires OpenGL ES version 2 -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat" >
<activity
android:name=".MapsActivity"
android:label="#string/app_name"
android:launchMode="singleTop" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<!-- Points to searchable activity -->
<meta-data android:name="android.app.default_searchable"
android:value=".MainActivity" />
<!-- Points to searchable meta data -->
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable"/>
</activity>
<provider
android:name=".PlaceProvider"
android:authorities="com.example.user.demo.PlaceProvider"
android:exported="false" />
<!-- Specifies the Android API Key, which is obtained from Google API Console -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="--------------------------------" />
</application>

MapView isn't showing 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();
}
}

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.

Android Google Maps API V2 not zooming to Location

Im not sure whats wrong but Im trying to get my google maps fragment to zoom in to a particular location on start. For some reason, it is not working and still zooms in to africa by default. Here is my code.
public class OutbreakMap extends Activity implements LocationListener {
double lat=50;
double longi=50;
private LocationManager locationManager;
private String provider;
private MapFragment mMapFragment;
private GoogleMap googleMap;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Check if enabled and if not send user to the GSP settings
// Better solution would be to display a dialog and suggesting to
// go to the settings
if (!enabled) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set title
alertDialogBuilder.setTitle("Turn On Your GPS");
// set dialog message
alertDialogBuilder
.setMessage("Please turn on your GPS to track sickness in your area!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
OutbreakMap.this.finish();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
Toast.makeText(getApplicationContext(),"Location not found",Toast.LENGTH_SHORT);
}
mMapFragment = MapFragment.newInstance();
FragmentTransaction fragmentTransaction =
getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.map, mMapFragment);
fragmentTransaction.commit();
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
setUpMapIfNeeded();
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
if(location != null) {
lat=location.getLatitude();
longi=location.getLongitude();
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(lat,longi)) // Sets the center of the map to Mountain View
.zoom(17) // Sets the zoom
// Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
UiSettings uiSettings=googleMap.getUiSettings();
uiSettings.setAllGesturesEnabled(false);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
Toast.makeText(getApplicationContext(),"Couldn't Find Location",Toast.LENGTH_SHORT);
}
ParseGeoPoint userLoc= new ParseGeoPoint(lat,longi);
ParseQuery query= new ParseQuery("Outbreak");
query.whereWithinMiles("location",userLoc,1);
query.findInBackground(new FindCallback() {
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
GetOutbreaks.getOutBreaksNearMe(googleMap,lat,longi,objects);
Toast.makeText(getApplicationContext(),"Recieved Outbreak Data",Toast.LENGTH_SHORT);
} else {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Could Not Download Data",Toast.LENGTH_SHORT);
}
}
});
// moveToPrescription();
// moveToPrescription();
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void moveToPrescription(){
Intent intent = new Intent(this,Prescription.class);
startActivity(intent);
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (googleMap != null) {
// The Map is verified. It is now safe to manipulate the map.
}
}
}
}
Also, here is my xml layout for the map fragment activity
<?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 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.MapFragment"/>
</LinearLayout>
And my Android manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.parse.starter"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="15"/>
<permission
android:name="com.example.mapdemo.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.example.mapdemo.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
<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"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
android:name="ParseApplication"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".ParseStarterProjectActivity"
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=".Register"/>
<activity android:name=".Login"/>
<activity android:name=".Home"/>
<activity android:name=".OutbreakMap"/>
<activity android:name=".Prescription"/>
<activity android:name=".MyPrescriptions"/>
<receiver android:name=".AlarmManagerBroadcastReceiver"></receiver>
<uses-library android:name="com.google.android.maps"/>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="My Maps API Key is Here"/>
</application>
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
</manifest>
The LogCat is not showing any errors. Thanks for the help!
You are adding second SupportMapFragment in code on top of Fragment having GoogleMap you interact with. Just remove unnecessary code.
Use SupportMapFragment
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
/>
GoogleMap gm;
gm = ((SupportMapFragment(getSupportFragmentManager().findFragmentById(R.id.map))).getMap();
Comment out the following lines of code
mMapFragment = MapFragment.newInstance();
FragmentTransaction fragmentTransaction =
getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.map, mMapFragment);
fragmentTransaction.commit();
and its going to work like a charm.

Categories

Resources