Today most applications are large, integrating GoolgeMap service and their application location to identify the user’s location or the user’s device. Typically, Grab, Uber, now … use GoogleMap and location to make it easy for users to move and locate customers. In this article, I will introduce how to integrate GoogleMap and device positioning. android inform on GoogleMap
GoogleMap integration
Configure and set up Manifest file
Open your build.gradle file and add this dependency to the android project
1 | implementation 'com.google.android.gms:play-services:12.0.1' |
Open Manifiest file to add some permissions
1 | <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> |
Add the following declaration to your manifying file inside the root element of the manifiest file.
1 | <uses-feature android:glEsVersion="0x00020000" android:required="true" /> |
Add the following declaration to your manifying file, You need to put it inside the Application tab
1 | <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> |
Add API key in project manifest and declare key API in values / string
1 | <meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/google_maps_key" /> |
Add the GoogleMap in MainActivity.XML object
1 | <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <fragment xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/map" android:name="com.google.android.gms.maps.MapFragment" android:layout_width="match_parent" android:layout_height="match_parent" /> </android.support.constraint.ConstraintLayout> |
Setting in MainActivity.java
1 | public class MainActivity extends AppCompatActivity implements OnMapReadyCallback { private GoogleMap mMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MapFragment mapFragment = (MapFragment) getFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; LatLng latLng = new LatLng(16.080141, 108.219977); CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10); mMap.animateCamera(cameraUpdate); } } |
Run the application and see the results
Locate Android on GoogleMap
Let’s start writing code
Add some permissions to locate
1 | <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> |
In MainActivity.java you implement the following objects: onnectionCallbacks, OnConnectionFailedListener and LocationListener
1 | public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { private GoogleMap mMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; 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 over riding // 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); } @Override public void onConnected(@Nullable Bundle bundle) { } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } @Override public void onLocationChanged(Location location) { } } |
Write a number of methods to locate
- setupLocationManager () – Use to create LocationManager before requesting endpoint location
- createdLocationRequest () – Processing required parameters to receive the endpoint location
- setInitialLocation () – This method displays the device’s last known Location on GoogleMap
Write a code for the setupLocationManager () method.
1 | private void setupLocationManager() { if (mGoogleApiClient == null) { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .addApi(Places.PLACE_DETECTION_API) .build(); } mGoogleApiClient.connect(); } |
Code for the createdLocationRequest method ()
1 | protected void createLocationRequest() { mLocationRequest = new LocationRequest(); mLocationRequest.setSmallestDisplacement(10); mLocationRequest.setFastestInterval(50000); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); mLocationRequest.setNumUpdates(3); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest); builder.setAlwaysShow(true); PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); result.setResultCallback(new ResultCallback<LocationSettingsResult>() { @Override public void onResult(@NonNull LocationSettingsResult result) { final Status status = result.getStatus(); final LocationSettingsStates states = result.getLocationSettingsStates(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: setInitialLocation(); break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: try { status.startResolutionForResult(MainActivity.this, 1); } catch (IntentSender.SendIntentException e) { } break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: break; } } }); } |
You need to process the result via OnActivityResult
1 | protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { switch (requestCode) { case 1: switch (resultCode) { case Activity.RESULT_OK: { setInitialLocation(); mRequestingLocationUpdates = true; break; } case Activity.RESULT_CANCELED: { mRequestingLocationUpdates = false; break; } default: { break; } } break; } } |
Code the setInitialLocation () method: this method is responsible for room on-screen location to your location.
1 | private void setInitialLocation() { if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.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; } LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, new LocationListener() { @Override public void onLocationChanged(Location location) { mLastLocation = location; try { LatLng positionUpdate = new LatLng(location.getLatitude(), location.getLongitude()); CameraUpdate update = CameraUpdateFactory.newLatLngZoom(positionUpdate, 15); mMap.animateCamera(update); } catch (Exception ex) { ex.printStackTrace(); Log.e("MapException", ex.getMessage()); } } }); } |
Handling location
Check the application version and ask the user to grant permission for the application version 6.0
1 | private void CheckMapPermission() { if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) { if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1002); }else { setupLocationManager(); } } else { setupLocationManager(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case 1002: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { setupLocationManager(); } } else { Toast.makeText(MainActivity.this,"Permission Denied",Toast.LENGTH_SHORT).show(); //finish(); } } break; } } |
Finally call the methods back to onCreate ()
1 | @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); CheckMapPermission(); createLocationRequest(); } |
Run the application and see the results: