1. Integration
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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=".MapsActivity" />
MainActivity.java
To get the GoogleMap object in our MainActivity.java class we need to implement the OnMapReadyCallback interface and override the onMapReady() callback method.
OnMapReadyCallback: This callback interface invokes when it instance is set on MapFragment object. The onMapReady(GoogleMap) method of OnMapReadyCallback interface is called when the map is ready to used. In the onMapReady(GoogleMap) method we can add markers, listeners and other attributes
package com.example.googlemapintegration;
import androidx.fragment.app.FragmentActivity;
import android.os.Bundle;
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 MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
@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;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 161);
mMap.addMarker(new MarkerOptions().position(sydney).title("sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
Permissions
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.googlemapintegration">
<!--
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:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!--
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>
Build.gradle (Module app)
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
Output
2. Customising your map
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//change the map type
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
//start the map at great wall of china and add a marker on it
// Add a marker in Sydney and move the camera
LatLng GWOC = new LatLng(40.4319077,116.5681862);
//change the the marker color or icon :-icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
mMap.addMarker(new MarkerOptions().position(GWOC).title("Great Wall of China").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
//add the zooming using newLatLngZoom(latlong value, zomming value from 1 to 20)
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(GWOC,5));
}
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//change the map type
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
//start the map at great wall of china and add a marker on it
// Add a marker in Sydney and move the camera
LatLng GWOC = new LatLng(40.4319077,116.5681862);
//change the the marker color or icon :-icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
mMap.addMarker(new MarkerOptions().position(GWOC).title("Great Wall of China").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
//add the zooming using newLatLngZoom(latlong value, zomming value from 1 to 20)
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(GWOC,5));
}
Output
3. Getting User Location & Showing the user Location on Map
LocationManager locationManager;
LocationListener locationListener;
Explicitly Request Permission above API Level 23(Marshmallow)
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1 /*could be any number*/);
} else {
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 0, 0, locationListener);
if you're on API Level 23 or Below use
if(Build.VERSION.SDK_INT < 23){
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 0, 0, locationListener);
}else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1 /*could be any number*/);
} else {
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 0, 0, locationListener);
Override the onRequestPermissionsResult method
@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 (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
}
Attach the LocationListener and override the onchanged method this method runs everytime your location changes
LocationListener: This interface is used to receive notification when the device location has changed. The abstract method of LocationListener onLocationChanged(Location) is called when the location has changed.
locationManager= (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener=new LocationListener() {
@Override
public void onLocationChanged(@NonNull Location location) {
LatLng GWOC = new LatLng(location.getLatitude(),location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(GWOC).title("My Location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(GWOC,10));
}
};
if you want to know the last known location everytime your app loads
Location lastKnownLocation=locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
LatLng GWOC = new LatLng(lastKnownLocation.getLatitude(),lastKnownLocation.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(GWOC).title("Last Known Location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(GWOC,5));
Complete code
package com.example.googlemapintegration;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;
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.security.Permission;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener 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);
}
@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 (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
}
@SuppressLint("MissingPermission")
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
locationManager= (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener=new LocationListener() {
@Override
public void onLocationChanged(@NonNull Location location) {
LatLng GWOC = new LatLng(location.getLatitude(),location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(GWOC).title("My Location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(GWOC,10));
}
};
//since we are on api level 29 we need to ask for permission
//if we are uisng api <23 then we dont need to ask permission explicitly
if(Build.VERSION.SDK_INT<23){
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 0, 0, locationListener);
}else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1 /*could be any number*/);
} else {
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 0, 0, locationListener);
//lets find the last known location everytime app loads the first location will be your last known location.
Location lastKnownLocation=locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
LatLng GWOC = new LatLng(lastKnownLocation.getLatitude(),lastKnownLocation.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(GWOC).title("Last Known Location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(GWOC,5));
}
}
//change the map type
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
//start the map at great wall of china and add a marker on it
// Add a marker in Sydney and move the camera
}
}
0 Comments