App crash when using getMapAsync() in MapsView - Android - java

I have a mapsview and it works fine when using getMap() although it shows me a depricated warning. But when i change getMap() to getMapAsync() the app will crash.
Here's my code
public class MapsActivity extends AppCompatActivity implements GoogleMap.OnInfoWindowClickListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnMarkerDragListener,
GoogleMap.OnInfoWindowCloseListener,
LocationListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMapAsync(this);
mMap.setOnInfoWindowClickListener(this);
mMap.setOnInfoWindowCloseListener(this);
mMap.setOnMarkerDragListener(this);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
markerPoints.add(latLng);
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(latLng);
}
});
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
//Getting the coordinates
toLatitude = marker.getPosition().latitude;
toLongitude = marker.getPosition().longitude;
dest = new LatLng(toLatitude, toLongitude);
mMap.animateCamera(CameraUpdateFactory.newLatLng(dest));
return ((toLatitude == my_marker.getPosition().latitude) && (toLongitude == my_marker.getPosition().longitude));
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setUpMap();
}
private void setUpMap() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
Toast.makeText(MapsActivity.this, "Anda harus menyetujuinya agar dapat menikmati semua fitur yang ada", Toast.LENGTH_LONG).show();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
}
}
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setTrafficEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder()
.zoom(15) // Sets the zoom
.target(new LatLng(-6.597629,106.79957))
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
Here's the xml layout
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
What's wrong with my code? Any help will be greatly appreciated.
Thanks.

I suppose that mMap is the GoogleMap object here.What you are doing is using mMap before it gets initialized so it must be throwing null pointer exception.
Make sure to use mMap object in onMapReady Callback.Hope it solves
your problem.So, in short all you need to do is place all your mMap
usages in onMap Ready callback

At the moment of getMapAsync call the onMapReady is not done. Be sure that ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) is not null or onMapReady() has finished with success.

Related

GPS application works on emualtor but not on my phone

My basic location application doesent work on my Galaxy A20 running API 29 but works fine on all my emuultors running the same API. im not sure what the problem could be as im not experianced with LOGCAT but the error states as following:
Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference.
THE ERROR IS ON LINE 117 on my project (At the end). But ive highlighted it here
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if (ContextCompat.checkSelfPermission(this , Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER ,0 ,0 , locationListener);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title("Marker in user house"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if (ContextCompat.checkSelfPermission(this , Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this , new String[]{Manifest.permission.ACCESS_FINE_LOCATION} , 1);
}
else{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER , 0 , 0 , locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude()); // ◅ THE ERROR OCCOURS HERE********
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title("Marker in user house"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
}
}
}
Maybe your phone has not managed to get a GPS fix yet. Check if lastKnowLocation is null before using it, and test the app outside where your phone can "see" the sky.

Getting java.lang.NullPointerException on googleMap.setMyLocationEnabled(true) Android Studio

So i am doing a project that i only need to get the location, i don't need to show the map or anything like that. I created the GoogleMap mGoogleMap; in the beginning of the class. When asking for the permission of location and course to the user i have this code:
public class Distance extends Activity implements Runnable {
//...
GoogleMap mGoogleMap;
protected LocationManager locationManager;
Location location;
//...
public void onCreate(Bundle savedInstanceState) {
//...
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
} else {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION},
TAG_CODE_PERMISSION_LOCATION);
}
//...
The first time i ran the application it worked but the other times got this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setMyLocationEnabled(boolean)' on a null object reference.
That error is in the line that have: mGoogleMap.setMyLocationEnabled(true);
I know that i need to initialize the googleMap object because it is blank but i don't know how. Help?
Init the map this way:
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
// Add a marker in Sydney, Australia, and move the camera.
LatLng sydney = new LatLng(-34, 151);
mGoogleMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}

My application is skipping frames when I open google maps. "The application may be doing too much work on its main thread"

I have been working on an app which implements google maps. When I am on my homescreen and presses the "start map" button the message "Skipped 85 frames! The application may be doing too much work on its main thread." is shown in the Android Monitor. I have been looking around for a solution but have not been able to find one that works for me. Does anyone have any idea how to prevent this?
My maps activity:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private boolean initiateApp;
double CO2data = 1.02;
double N2data = 0.002;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
initiateApp = true;
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
/* Here we create the infoWindow **/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
public View getInfoWindow(Marker arg0) {
View v = getLayoutInflater().inflate(R.layout.custom_infowindow, null);
TextView tv = (TextView) v.findViewById(R.id.infoText);
tv.setText("CO2 data: "+String.valueOf(CO2data) +"\n" + "N2 data: "+String.valueOf(N2data));
return v;
}
public View getInfoContents(Marker arg0) {
return null;
}
});
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(2000);
mLocationRequest.setFastestInterval(2000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
Log.d("ADebugTag", "Value: " + Double.toString(location.getLatitude()));
Log.d("ADebugTag", "Value: " + Double.toString(location.getLongitude()));
//move map camera
if(initiateApp){
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
}
initiateApp = false;
boolean contains = mMap.getProjection()
.getVisibleRegion()
.latLngBounds
.contains(latLng);
if(!contains){
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
}
My maps XML
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.kasper.map_app.MapsActivity" />
Based from this thread, if you have a lot of code in your UI events then you will see this error message. Also this will occur with asynchronous events like fetching data from a URL. The workaround given is to use threads or async tasks.
You want to off load any heavy code off of your UI Threads and onto another area - a new thread or in your main activity.
Here are some SO posts which might also help:
The application may be doing too much work on its main thread
The application may be doing too much work on its main thread - Android

MapsActivity crashing on load

Hey Im new to Android and wondering if someone can help me. I have a MapsActivity which crashes when navigating to it. I think I've narrowed down to exactly where it is from looking through the errors but I cant figure out what to change.
I've added the whole MapsActivity class below. The problem is occuring in the onConnected method on this line mLocationManager.requestLocationUpdates(provider, 5000, 0, this);
. Android Studio recommends I cast 'this' to LocationListener but this doesn't work and the error I get from doing so is listed below the MapsActivity code.
I have also tried entering mLocationListener in the place of 'this' but doesn't work and I get errors which are listed below too.
ANY HELP IS GREATLY APPRECIATED. THANKS!
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private static final int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 2;
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private LocationManager mLocationManager;
private Location mLastLocation;
private LocationListener mLocationListener;
private String mLatitude;
private String mLongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
//create instance of location manager and get location service
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
#Override
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
//mLocationManager.removeUpdates((LocationManager) this);
super.onStop();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(true);
criteria.setBearingRequired(true);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = mLocationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationManager.requestLocationUpdates(provider, 5000, 0, this);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null){
mLatitude = String.valueOf(mLastLocation.getLatitude());
mLongitude = String.valueOf(mLastLocation.getLongitude());
Toast.makeText(this, mLatitude + " , " + mLongitude, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Permission denied, please accept permission..", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults){
switch (requestCode){
case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION:{
//if request cancelled the results array is empty
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//do task you wish to do
//Intent intent = (new Intent(this, MapsActivity.class));
//startActivity(intent);
}else{
//permission denied, disable functionality(GPS)
}
return;
}
//other cases go here
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
}
}
Casting errors -
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.a8460p.locationotes, PID: 23305
java.lang.ClassCastException: com.example.a8460p.locationotes.MapsActivity cannot be cast to android.location.LocationListener
at com.example.a8460p.locationotes.MapsActivity.onConnected(MapsActivity.java:106)
at com.google.android.gms.common.internal.zzm.zzq(Unknown Source)
at com.google.android.gms.internal.zzaal.zzo(Unknown Source)
at com.google.android.gms.internal.zzaaj.zzvE(Unknown Source)
at com.google.android.gms.internal.zzaaj.onConnected(Unknown Source)
at com.google.android.gms.internal.zzaan.onConnected(Unknown Source)
at com.google.android.gms.internal.zzzy.onConnected(Unknown Source)
at com.google.android.gms.common.internal.zzl$1.onConnected(Unknown Source)
at com.google.android.gms.common.internal.zzf$zzj.zzwZ(Unknown Source)
at com.google.android.gms.common.internal.zzf$zza.zzc(Unknown Source)
at com.google.android.gms.common.internal.zzf$zza.zzu(Unknown Source)
at com.google.android.gms.common.internal.zzf$zze.zzxa(Unknown Source)
at com.google.android.gms.common.internal.zzf$zzd.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Replacing 'this' with mLocationListener errors -
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.a8460p.locationotes, PID: 24073
java.lang.IllegalArgumentException: invalid listener: null
at android.location.LocationManager.checkListener(LocationManager.java:1733)
at android.location.LocationManager.requestLocationUpdates(LocationManager.java:461)
at com.example.a8460p.locationotes.MapsActivity.onConnected(MapsActivity.java:106)
at com.google.android.gms.common.internal.zzm.zzq(Unknown Source)
at com.google.android.gms.internal.zzaal.zzo(Unknown Source)
at com.google.android.gms.internal.zzaaj.zzvE(Unknown Source)
at com.google.android.gms.internal.zzaaj.onConnected(Unknown Source)
at com.google.android.gms.internal.zzaan.onConnected(Unknown Source)
at com.google.android.gms.internal.zzzy.onConnected(Unknown Source)
at com.google.android.gms.common.internal.zzl$1.onConnected(Unknown Source)
at com.google.android.gms.common.internal.zzf$zzj.zzwZ(Unknown Source)
at com.google.android.gms.common.internal.zzf$zza.zzc(Unknown Source)
at com.google.android.gms.common.internal.zzf$zza.zzu(Unknown Source)
at com.google.android.gms.common.internal.zzf$zze.zzxa(Unknown Source)
at com.google.android.gms.common.internal.zzf$zzd.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Make MapsActivity implements android.location.LocationListener instead of com.google.android.gms.location.LocationListener
For First crash: this crash is occuring due to the incorrect import for location listener class which you have implements to your Activity.
Change com.google.android.gms.location.LocationListener with android.location.LocationListener
and for second crash use bellow LocationListener, this crash is occuring due your null reference of location listener object.
private LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
Your requestLocationUpdates could not find instance of Listener so add MapsActivity.this to requestLocationUpdates
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationManager.requestLocationUpdates(provider, 5000, 0, MapsActivity.this);//Changed here
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null){
mLatitude = String.valueOf(mLastLocation.getLatitude());
mLongitude = String.valueOf(mLastLocation.getLongitude());
Toast.makeText(this, mLatitude + " , " + mLongitude, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Permission denied, please accept permission..", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}

How to set location on start - Google Maps API V2

Hi currently when i start the application it shows the whole map of the world, when i press the gps button then it zooms into my current location. I want it that when the activity starts it already zooms into your current location. Here is the source code:
public class MainActivity extends Activity {
// Google Map
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// Loading map
initilizeMap();
// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
/**
* function to load map If map is not created it will create it for you
* */
private void initilizeMap() {
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();
}
}
}
}
You need to get Current Location using Location Listener and animate Camera on that.
First implement LocationListener to your Activity like:
public class BasicMapActivity_new extends Activity implements LocationListener
Now Implement following code in your Activity onCreate(....)
private LocationManager locationManager;
private String provider;
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!enabledGPS) {
Toast.makeText(BasicMapActivity_new.this, "GPS signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
else if(!enabledWiFi){
Toast.makeText(BasicMapActivity_new.this, "Network signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// 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);
//getCurrentLocation();
// Initialize the location fields
if (location != null) {
// Toast.makeText(BasicMapActivity_new.this, "Selected Provider " + provider,
//Toast.LENGTH_SHORT).show();
onLocationChanged(location);
} else {
//do something
}
initilizeMap();
And now implement onLocationChanged(.....)
Marker startPerc=null;
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng coordinate = new LatLng(lat, lng);
startPerc = mMap.addMarker(new MarkerOptions()
.position(coordinate)
.title("Current Location")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 18.0f));
}
And also implement
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
initilizeMap();
}
And also add below permission in your manifest.xml file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I guess you could use something like :
function initialize() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 5,
center: new google.maps.LatLng(53.671068, -130.25128),
mapTypeId: google.maps.MapTypeId.TERRAIN
});
Google developer page has a lot of sample code using Google Maps API. Check this out : Simple Google Maps
Thanks,
Noel

Categories