How do i get my code to give my current location? - android

I am trying to get my code to zoom in and give me my exact location once I open the map activity, but instead, I get a map showing the map of Africa.
I have written some codes I got from tutorials online, but none has succeeded in giving what I want.
I tried to use this link
Also tried to use this YouTube video
MapActivity.java:
package com.kiki.doctorlocation;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MapActivity extends FragmentActivity implements
OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private GoogleMap mMap;;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
//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);
}
}
private void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
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 onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Showing Current Location Marker on Map
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), true);
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
Location locations = locationManager.getLastKnownLocation(provider);
List<String> providerList = locationManager.getAllProviders();
if (null != locations && null != providerList && providerList.size() > 0) {
double longitude = locations.getLongitude();
double latitude = locations.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(),
Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(latitude,
longitude, 1);
if (null != listAddresses && listAddresses.size() > 0) {
String state = listAddresses.get(0).getAdminArea();
String country = listAddresses.get(0).getCountryName();
String subLocality = listAddresses.get(0).getSubLocality();
markerOptions.title("" + latLng + "," + subLocality + "," + state
+ "," + country);
}
} catch (IOException e) {
e.printStackTrace();
}
}
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
mCurrLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
this);
}
}
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
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, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "permission denied",
Toast.LENGTH_LONG).show();
}
return;
}
}
}
}
I expect when I run my code, my map to zoom in and give my current exact location. The code has no errors, that is why I need help.

I will try and assist. I will assume you have all the requisite libraries in your gradle. Check if you have
implementation 'com.google.android.gms:play-services-maps:16.1.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.google.android.libraries.places:places:1.0.0'
Also confirm if you have the following permissions (on top of the others you might have)
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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.ACCESS_WIFI_STATE" />
On newer Android Version, you might need to request the permissions on runtime. You can add the stub on your activity.
public static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
//Invoking the above function
String[] PERMISSIONS = {Manifest.permission.INTERNET,Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.CAMERA };
if (!hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, 1);
}
Your activity could look like this.
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.model.TypeFilter;
import com.google.android.libraries.places.widget.AutocompleteSupportFragment;
import com.google.android.libraries.places.widget.listener.PlaceSelectionListener;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
public class SetPickUpLocation extends FragmentActivity implements OnMapReadyCallback {
SupportMapFragment mapFragment;
private GoogleMap mMap;
private GoogleMap.OnCameraIdleListener onCameraIdleListener;
private TextView resutText;
private FusedLocationProviderClient fusedLocationProviderClient;
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 5445;
private Location currentLocation;
public static String latitude = null, longitude = null, location = null, area = null;
private boolean firstTimeFlag = true;
Button setLocation;
View mapView;
AutocompleteSupportFragment autocompleteFragment;
String TAG = "Google_Places";
int AUTOCOMPLETE_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.set_pickup_location);
resutText = (TextView) findViewById(R.id.dragg_result);
setLocation = (Button) findViewById(R.id.setLocation);
autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mapView = mapFragment.getView();
Toast.makeText(SetPickUpLocation.this, ConstantValues.DRAG_MAP_MARKER, Toast.LENGTH_SHORT).show();
configureCameraIdle();
Places.initialize(getApplicationContext(), ConstantValues.GOOGLE_API_KEY);
setLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (latitude != null && longitude != null) {
//you can put your logic here
}else{
//you can put your logic here
}
}
});
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME , Place.Field.LAT_LNG));
//autocompleteFragment.setTypeFilter(TypeFilter.REGIONS);
autocompleteFragment.setCountry("KE");
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
//Log.d(TAG , place.getName() + ", " + place.getId());
if(mMap != null){
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(place.getLatLng(), 16);
mMap.animateCamera(cameraUpdate);
autocompleteFragment.setText("");
}
//
//mMap.mo
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.d(TAG , "An error occurred: " + status);
}
});
}
#Override
protected void onStop() {
super.onStop();
if (fusedLocationProviderClient != null)
fusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
}
#Override
protected void onResume() {
super.onResume();
if (isGooglePlayServicesAvailable()) {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
startCurrentLocationUpdates();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
fusedLocationProviderClient = null;
mMap = null;
}
private void configureCameraIdle() {
onCameraIdleListener = new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
LatLng latLng = mMap.getCameraPosition().target;
Geocoder geocoder = new Geocoder(SetPickUpLocation.this);
try {
List<Address> addressList = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (addressList != null && addressList.size() > 0) {
String locality = addressList.get(0).getAddressLine(0);
String country = addressList.get(0).getCountryName();
latitude = Double.toString(latLng.latitude);
longitude = Double.toString(latLng.longitude);
if (!locality.isEmpty() && !country.isEmpty()) {
resutText.setText(locality);
location = locality;
try{
String city = addressList.get(0).getAdminArea();
if(!city.isEmpty()){
area = city;
}
}catch (Exception e){
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnCameraIdleListener(onCameraIdleListener);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
if (mapView != null &&
mapView.findViewById(Integer.parseInt("1")) != null) {
// Get the button view
View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
// and next place it, on bottom right (as Google Maps app)
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
locationButton.getLayoutParams();
// position on right bottom
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
layoutParams.setMargins(0, 0, 100, 330);
}
}
private final LocationCallback mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult.getLastLocation() == null)
return;
currentLocation = locationResult.getLastLocation();
if (firstTimeFlag && mMap != null) {
animateCamera(currentLocation);
firstTimeFlag = false;
}
//showMarker(currentLocation);
}
};
private void startCurrentLocationUpdates() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(3000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
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) {
ActivityCompat.requestPermissions(SetPickUpLocation.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
return;
}
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, mLocationCallback, Looper.myLooper());
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status)
return true;
else {
if (googleApiAvailability.isUserResolvableError(status))
Toast.makeText(this, "Please Install google play services to use this application", Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED)
Toast.makeText(this, "Permission denied by uses", Toast.LENGTH_SHORT).show();
else if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
startCurrentLocationUpdates();
}
}
private void animateCamera(#NonNull Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(getCameraPositionWithBearing(latLng)));
}
#NonNull
private CameraPosition getCameraPositionWithBearing(LatLng latLng) {
return new CameraPosition.Builder().target(latLng).zoom(16).build();
}
}
The XML Layout (you can use your own ViewGroups)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".orders.SetPickUpLocation">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.v7.widget.CardView
android:id="#+id/idCardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
app:cardCornerRadius="4dp">
<fragment
android:id="#+id/autocomplete_fragment"
android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.v7.widget.CardView>
<ImageView
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/ic_google_map_marker"
android:text="TextView" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#ffffff"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="#dimen/activity_horizontal_margin"
android:paddingBottom="#dimen/activity_horizontal_margin"
android:weightSum="3">
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.2"
android:gravity="center_vertical"
android:src="#drawable/ic_google_map_marker" />
<TextView
android:id="#+id/dragg_result"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="2.8"
android:fontFamily="#font/museo"
android:gravity="left"
android:paddingLeft="3dp"
android:text="Select this location"
android:textColor="#000"
android:textSize="18dp" />
</LinearLayout>
<Button
android:id="#+id/setLocation"
style="?android:attr/borderlessButtonStyle"
android:layout_width="match_parent"
android:layout_height="65dp"
android:layout_marginBottom="#dimen/activity_horizontal_margin"
android:fontFamily="#font/museo"
android:text="Select this location"
android:textColor="#ffffff"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
</RelativeLayout>
I hope this helps and also use your own icons/drawables as I have not included them here.

So the previous answer didn't work for me so i decide to sort another way out and this is the the code that is working for me
MapActivity.java
import android.app.Dialog;
import android.content.pm.PackageManager;
import android.location.Address;
imsport android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (GSA()) {
Toast.makeText(this, "Services perfect", Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_map);
initMap();
} else {
}
}
private void initMap() {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync((OnMapReadyCallback) this);
}
public boolean GSA() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int isAvailable = googleApiAvailability.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS)
return true;
else if (googleApiAvailability.isUserResolvableError(isAvailable)) {
Dialog dialog = googleApiAvailability.getErrorDialog(this, isAvailable, 0);
dialog.show();
} else {
Toast.makeText(this, "Can't connect to Google services", Toast.LENGTH_SHORT).show();
}
return false;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// gotoLocationzoom(-1.276680, 36.904785, 15);
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) {
// TODO: Consider calling
// Activity#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
// LatLng sydney = new LatLng(-1.276680, 36.904785);
// googleMap.addMarker(new MarkerOptions().position(sydney)
// .title("Marker in white hse"));
// googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
private void gotoLocationzoom (double lat, double lng, float zoom){
LatLng latLng = new LatLng(lat,lng);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng,zoom);
mMap.animateCamera(cameraUpdate);
}
public void search(View view) throws IOException {
EditText et = (EditText) findViewById(R.id.editText);
String location = et.getText().toString();
Geocoder geocoder = new Geocoder(this);
List<Address> list = geocoder.getFromLocationName(location,1);
Address address = list.get(0);
String locality = address.getLocality();
Toast.makeText(this, locality, Toast.LENGTH_SHORT).show();
double lat = address.getLatitude();
double lng = address.getLongitude();
gotoLocationzoom(lat,lng,15);
LatLng latLng = new LatLng(lat,lng);
mMap.addMarker(new MarkerOptions().position(latLng).title(location).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
}
}
activity_map.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapActivity">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="500dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="0dp"
tools:context="com.example.mapwithmarker.MapsMarkerActivity" />
<EditText
android:id="#+id/editText"
android:layout_width="291dp"
android:layout_height="59dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginEnd="115dp"
android:layout_marginRight="115dp"
android:ems="10"
android:hint="Enter your destination"
android:inputType="textPersonName" />
<Button
android:id="#+id/button"
android:layout_width="100dp"
android:layout_height="59dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginEnd="17dp"
android:layout_marginRight="17dp"
android:onClick="search"
android:text="search" />
</RelativeLayout>
permissions i added to my AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE.EXTERNAL.STORAGE"/>
<uses-permission android:name="com.google.androidproviders.gsf.permissions.READ.GSERVICES"/>
<uses-permission android:name="com.kiki.doctorlocation.permission.MAPS.RECEIVE"/>
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
<permission android:name="com.kiki.doctorlocation.permission.MAPS.RECEIVE" android:protectionLevel="signature"/>
This is the code that worked for me...Thanks for the insights though

Related

Android Maps SDK not getting current location

I am trying to display a users current location using the google map activity. when the activity is launched the google map is displayed as it should be, but there is no marker and the users current location is not gotten. The map displays a view over many different countries. After putting Toast messages in every method i realise onLocationChange is not being called, as no Toast appears for this method.
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
{
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location lastKnownLocation;
private Marker userLocationMarker;
private static final int REQUEST_USER_LOCATION_CODE = 99;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M)
{
checkPermissions();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap)
{
// Get the users current location
mMap = googleMap;
// Check that the access permissions are granted by the device
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient()
{
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
public void onLocationChanged(Location location)
{
lastKnownLocation = location;
if(userLocationMarker != null)
{
// Remove that marker as if marker already exists it is likely wrong
userLocationMarker.remove();
}
// Get users longitude and latitude
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
// Display Marker on users current location
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("You are Here");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET));
userLocationMarker = mMap.addMarker(markerOptions);
//Focus map on users current location
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(1));
if(googleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle)
{
// Update map while user is currently moving
locationRequest= new LocationRequest();
locationRequest.setInterval(1100);
locationRequest.setFastestInterval(1100);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i)
{
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult)
{
}
private boolean checkPermissions()
{
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_USER_LOCATION_CODE);
}
else
{
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_USER_LOCATION_CODE);
}
return false;
}
else
{
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
switch(requestCode)
{
case REQUEST_USER_LOCATION_CODE:
if(grantResults.length > 0 && grantResults[0]== PackageManager.PERMISSION_GRANTED)
{
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
if(googleApiClient == null)
{
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
}
else
{
Toast.makeText(this, "Permission Denied", Toast.LENGTH_LONG).show();
}
}
}
}
Permissions
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
In order to display user location you should add:
mMap.setMyLocationEnabled(true);
on your onMapReady callback, there's no need to use a LocationRequest.
Be aware that you'll be able to get user position after your app has achieved location permissions. To do so you can follow this guide or use a third party library like easy permissions
After hours of research the answer was in front of me, the location settings were disabled in the phone settings. Witting this so the next person inst as stupid as me.

Android Studio GoogleMaps in Fragment

I want to put the map of Google Maps in my sección with marks and my localitation, but when i put this section, this app closes. And It says ERROR MapFragment.java:83 " LatLng sydney = new LatLng(Float.parseFloat("Lat")".
I put my two code's files:
fragment_map.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<com.google.android.gms.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
MapFragment.java
package com.example.julianrc1.petracecitm;
import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
*/
public class MapFragment extends Fragment {
public MapFragment() {
// Required empty public constructor
}
MapView mMapView;
private GoogleMap googleMap;
ArrayList<LatLng> markerPoints;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_map, container, false);
mMapView= (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
if (checkLocationPermission()) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
googleMap.setMyLocationEnabled(true);
}
}
markerPoints = new ArrayList<LatLng>();
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(Float.parseFloat("Lat"), Float.parseFloat("Long"));
googleMap.addMarker(new MarkerOptions().position(sydney).
title("Title").snippet("TitleName"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition
(cameraPosition ));
}
});
return rootView;
}
#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();
}
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
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.
new AlertDialog.Builder(getActivity())
.setTitle("")
.setMessage("")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(getActivity(),new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
1);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1:
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true);
}
} else {
}
return;
}
}
}
}
Thank you so much for help me!!!
Replace this
LatLng sydney = new LatLng(Float.parseFloat("Lat")
with
LatLng sydney = new LatLng(33.8688,151.2093)

map is not displayed (blank)

I use the following code to display Google map on my Android app (taken from here).
MapActivity.java
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import android.Manifest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
public class MapActivity extends AppCompatActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
MapView mv;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
getSupportActionBar().setTitle("Map Location Activity");
// uncomment this and code will crash. still not sure why? :(
//mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// mapFrag.getMapAsync(this);
mv = (MapView) findViewById(R.id.map);
mv.getMapAsync(this);
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
mGoogleMap.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) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
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 onConnectionFailed(ConnectionResult connectionResult) {}
#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.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
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.
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MapActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
#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, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! 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
}
}
}
activity_map.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="app.devbyzero.net.pascasarjanatrisakti.MapActivity">
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="visible" />
</android.support.constraint.ConstraintLayout>
In the AndroidManifest.xml, I've added these part:
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
And of course in strings.xml, I have something like this:
<string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">xxxxxxxxxxxxxxxxxxxxxx</string>
When the app is run, there is not map drawn at all. Blank. I tried to debug the code a few times, and couldn't find any significant line in logcat (maybe I missed that). What could be possibly wrong here?
The first issue I see with your code is you need to call the mv.onCreate(this) before calling mv.getMapAsync().
I am looking into your code further to see if there are any other issues.
Lifecycle of a MapView https://developers.google.com/android/reference/com/google/android/gms/maps/MapView
Also the only time you call mGoogleMap.moveCamerais in onLocationChanged can you try setting an initial location in onMapReady and see if the map shows up. Something like this

onLocationChanged called only the first time i open the application, but not anymore if app becomes inactive and active again

i'm trying to build a GPS app with Android Studio. It's working okay on the first run but whenever i close the app and open it again or go to desktop and back into it, as i have figured until now, my LocationListener doesn't get called anymore.
Practically what happens is that it doesn't display my location as intended the second time. No error no anything.
Here's my code, thanks in advance if you can help. I've been searching a lot :(
package com.madnzz.googlemapsstuff;
import android.*;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Camera;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.GroundOverlay;
import com.google.android.gms.maps.model.GroundOverlayOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.sql.Time;
import java.util.Random;
import com.google.android.gms.appindexing.AndroidAppUri;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import static com.madnzz.googlemapsstuff.R.id.activity_chooser_view_content;
import static com.madnzz.googlemapsstuff.R.id.repositionButton;
/*
TODO: Replace retard user icon with improved one
*IMPLEMENT the way the user is facing. http://android-coding.blogspot.ro/2012/03/create-our-android-compass.html
*
TODO: implement GPS routes https://www.youtube.com/watch?v=CCZPUeY94MU or http://wptrafficanalyzer.in/blog/drawing-driving-route-directions-between-two-locations-using-google-directions-in-google-map-android-api-v2/
*REPLACE consumed path with cookie crumb graphic
TODO: save path and able to share with others.
TODO later: Battery efficiency https://developer.android.com/guide/topics/location/strategies.html
*/
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) {
startListening();
}
}
}
public void startListening() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
}
Random random=new Random();
GroundOverlayOptions[] c00kieCrumb=new GroundOverlayOptions[200];
int i=0;
///////////////////////////////////////////////////////////////////////////////
public void addCrumb(LatLng userLocation){
int randomCrumbBearing=random.nextInt(36)*10;
c00kieCrumb[i] = new GroundOverlayOptions()
.image(BitmapDescriptorFactory.fromResource(R.drawable.frateeeee))
.position(userLocation, 3,3).bearing(randomCrumbBearing);
c00kieCrumb[i].isVisible();
i++;
for (int j = 0; j < i; j++) {
mMap.addGroundOverlay(c00kieCrumb[j]);
}
}//adds new cookie crumb to user location
public void putCrumbConditions(LatLng userLocation){
for (int j = 0; j < i; j++) {
mMap.addGroundOverlay(c00kieCrumb[j]);
}
if (i == 0) {
addCrumb(userLocation);
} else {
if (Math.abs((c00kieCrumb[i - 1].getLocation().latitude - userLocation.latitude)) > 0.00003
|| Math.abs(c00kieCrumb[i - 1].getLocation().longitude - userLocation.longitude) > 0.00003) {
addCrumb(userLocation);
}
}
}//adds a new cookie crumb to the user location 4
// IF THE USER IS 0.00003 UNITS AWAY FROM LAST CRUMB PLACED
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("ZiciCinci created shit", "Am ajuns aici");
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);
}
#Override
protected void onDestroy(Bundle savedInstanceState){
super.onDestroy();
}
LatLng [] locationCalibrator,savedUserLocation;
LatLng userLocation,previousUserLocation;
Boolean gpsCalibrationInProgress,tooClose,firstIteration,mapCenteredOnUserPosition,cameraFollowUserPosition;
int locationIteration=0,savedUserLocationPos;
ImageButton repositionButton;
#Override
public void onMapReady(GoogleMap googleMap) {
Log.i("ZiciPatru map is ready","Am ajuns aici");
mMap = googleMap;
c00kieCrumb[0] = new GroundOverlayOptions();
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationCalibrator = new LatLng[100];
gpsCalibrationInProgress = true;
locationIteration = 0;
i = 0;
savedUserLocation = new LatLng[3];
savedUserLocationPos = 0;
tooClose = true;
firstIteration = true;
mapCenteredOnUserPosition = true;
cameraFollowUserPosition = true;
previousUserLocation = new LatLng(0, 0);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i("Zici3 gps calibration","Am ajuns aici");
userLocation = new LatLng(location.getLatitude(), location.getLongitude());
if (!gpsCalibrationInProgress) {
if (Math.abs(previousUserLocation.latitude - userLocation.latitude) > 0.000003 ||
Math.abs(previousUserLocation.latitude - userLocation.longitude) > 0.000003) {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.edytardin64x64)).rotation(0));
if (firstIteration) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
firstIteration = false;
}
LatLng userDestination = new LatLng(44.4187432, 26.1556372);
mMap.addMarker(new MarkerOptions().position(userDestination).title("COOOOKIESTUFF").icon(BitmapDescriptorFactory.fromResource(R.drawable.c00ki3_marker_128x128)));
putCrumbConditions(userLocation);
}
} else {
Toast.makeText(getApplicationContext(), "Calibrating gps, please stand still", Toast.LENGTH_SHORT).show();
locationCalibrator[locationIteration] = userLocation;
locationIteration++;
if (locationIteration >= 2) {
if (Math.abs(locationCalibrator[locationIteration - 1].latitude - userLocation.latitude) < 0.0001
&& Math.abs(locationCalibrator[locationIteration - 1].longitude - userLocation.longitude) < 0.0001
&& Math.abs(locationCalibrator[locationIteration - 2].latitude - userLocation.latitude) < 0.0001
&& Math.abs(locationCalibrator[locationIteration - 2].latitude - userLocation.latitude) < 0.0001) {
gpsCalibrationInProgress = false;
}
}
}
previousUserLocation = userLocation;
repositionButton = (ImageButton) findViewById(R.id.repositionButton);
repositionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("rarara","q");
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
repositionButton.setBackgroundResource(R.drawable.location_centered);
mapCenteredOnUserPosition = true;
cameraFollowUserPosition = true;
}
});
if (mapCenteredOnUserPosition) {
mMap.setOnCameraMoveStartedListener(new GoogleMap.OnCameraMoveStartedListener() {
#Override
public void onCameraMoveStarted(int reason) {
if (reason == GoogleMap.OnCameraMoveStartedListener.REASON_GESTURE) {
repositionButton.setBackgroundResource(R.drawable.location_not_centered);
mapCenteredOnUserPosition = false;
cameraFollowUserPosition = false;
}
}
});
}
if (cameraFollowUserPosition) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
repositionButton.setBackgroundResource(R.drawable.location_centered);
}
LocationServices.FusedLocationApi.removeLocationUpdates(GoogleApiClient,this)
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(getApplicationContext(), "Please activate your location", Toast.LENGTH_SHORT);
}
};
if (Build.VERSION.SDK_INT < 23) {
startListening();
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLocation != null) {
LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
if (!tooClose) {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.edytardin64x64)));
}
tooClose = false;
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
}
}
My android manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.madnzz.googlemapsstuff">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:exported="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!--
android:roundIcon="#mipmap/ic_launcher_round"
-->
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
And layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity" >
<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.madnzz.googlemapsstuff.MapsActivity"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<ImageButton
android:id="#+id/repositionButton"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="40dp"
android:layout_marginEnd="30dp"/>
<!--android:onClick="repositionMap"-->
android:background="#drawable/location_not_centered" />
</RelativeLayout>
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLocation != null) {
LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(),
lastKnownLocation.getLongitude());
if (!tooClose) {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.edytardin64x64)));
}
tooClose = false;
} else {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
The problematic part of the your code(and also scenario),
You did make location request if lastKnownLocationis null. After receiving new location one time(onLocationChanged), getLastKnownLocationwill not return null, and location request will not be called for later starts(except boot)
As a result, onLocationChanged called only one time.
getLastKnownLocation will give you the latest location obtained from given provider.It's possible to get null. You just used GPS_PROVIDER but could also try NETWORK_PROVIDER too
mGpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mNetworkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
With this you can increase chance of getting a location. If both of them null then make location request provider(s) (sorry there is no magic, you must, like others do)

Application Crashes While Finding current Location on Button Click

My Problem Is while the app to running. The onClick function should call my position from GPS by longitude, latitude. But the problem is the app crashes when the button is clicked. What is the solution for this? I have tried to follow instructions from older Stack questions, but the error persists.
Here's the debug message:
-----------------------------------------------------------------------------------------------------------------------------------
java.lang.NullPointerException: Attempt to
invoke virtual method 'void
com.google.android.gms.maps.GoogleMap.animateCamera(com.google.android.gms.maps.CameraUpdate)'
on a null object reference
at
com.booleandev.googlfind.MainActivity.onClick(MainActivity.java:97)
-----------------------------------------------------------------------------------------------------------------------------------
public void onClick(View v) {
if (v == koordinat) {
if (latitude != 0 && longitude != 0) {
Toast.makeText(getApplicationContext(), "Latitude : " + latitude + " Longitude : " + longitude, Toast.LENGTH_LONG).show();
}
}
if (v == posisi_user) {
LatLng user = new LatLng(latitude, longitude);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
user, 12));
}
}
this is my full MainActivity.java
package com.booleandev.googlfind;
import android.*;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity implements LocationListener, OnMapReadyCallback,View.OnClickListener {
GoogleMap googleMap;
double latitude;
double longitude;
Button koordinat;
Button posisi_user;
private final static int MY_PERMISSION_FINE_LOCATION = 101;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
koordinat = (Button) findViewById(R.id.koordinat);
posisi_user = (Button) findViewById(R.id.posisi_user);
koordinat.setOnClickListener(this);
posisi_user.setOnClickListener(this);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
fm.getMapAsync(this);
CekGPS();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// googleMap.setMyLocationEnabled(true);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_FINE_LOCATION);
}
}
if (latitude != 0 && longitude != 0) {
Toast.makeText(getApplicationContext(), "Latitude : " + latitude + " Longitude : " + longitude, Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View v) {
if (v == koordinat) {
if (latitude != 0 && longitude != 0) {
Toast.makeText(getApplicationContext(), "Latitude : " + latitude + " Longitude : " + longitude, Toast.LENGTH_LONG).show();
}
}
if (v == posisi_user) {
LatLng user = new LatLng(latitude, longitude);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
user, 12));
}
}
public void CekGPS() {
try {
/* pengecekan GPS hidup / tidak */
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Info");
builder.setMessage("Anda akan mengaktifkan GPS?");
builder.setPositiveButton("Ya",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
Intent i = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
});
builder.setNegativeButton("Tidak",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
builder.create().show();
}
} catch (Exception e) {
}
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
// menampilkan status google play service
if (status != ConnectionResult.SUCCESS) {
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else {
// Google Play Services tersedia
try {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Membuat kriteria untuk penampungan provider
Criteria criteria = new Criteria();
// Mencari provider terbaik
String provider = locationManager.getBestProvider(criteria,
true);
// Mendapatkan lokasi terakhir
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
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) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(provider, 5000, 0, this);
} catch (Exception e) {
}
}
}
#Override
public void onLocationChanged(Location lokasi) {
// TODO Auto-generated method stub
latitude =lokasi.getLatitude();
longitude = lokasi.getLongitude();
}
#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
}
public void onMapReady(GoogleMap googleMap) {
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setTrafficEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSION_FINE_LOCATION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true);
}
}
else {
Toast.makeText(getApplicationContext(), "GPS TURN OFF", Toast.LENGTH_SHORT).show();
finish();
}
break;
}
}
}
my activity_main.xml too
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/home_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="10"
>
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="9"
android:name="com.google.android.gms.maps.SupportMapFragment"
class="com.google.android.gms.maps.SupportMapFragment"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/koordinat"
style="?android:attr/borderlessButtonStyle"
android:textStyle="bold"
android:layout_height="wrap_content"
android:text="Koordinat User"
android:layout_weight="1"
android:layout_width="0dp" />
<Button
style="?android:attr/borderlessButtonStyle"
android:id="#+id/posisi_user"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Posisi User"/>
</LinearLayout>
</LinearLayout>
the manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<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-permission android:name="com.google.android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.permission.ACCESS_COARSE_LOCATION" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="Secret" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity android:name=".lokasi">
</activity>
<activity android:name=".spalsh">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
You have not initialized the googlemap variable in on map ready
Like this.googleMap=googleMap;
public void onMapReady(GoogleMap googleMap) {
this.googleMap=googleMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setTrafficEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
}
TRY THIS

Categories

Resources