Table of Contents
ToggleIntroduction:
how to Enable GPS Location On Webview, Location-based services are increasingly important in many mobile applications today. With the help of the robust development tools offered by Android Studio, developers may incorporate web content into their Android apps, including WebView. The user experience can be improved and location-based functionality made available by turning on GPS location in WebView. In this blog article, we’ll show you how to use Android Studio to enable GPS location in WebView.
Step 1: Set Up the Project
Before we begin, ensure that you have Android Studio installed on your machine. Create a new Android project or open an existing one in Android Studio.
Step 2: Add Permissions to AndroidManifest.xml
how to enable GPS location on WebView, we need to add the necessary permissions to the AndroidManifest.xml file. Open the file and add the following lines of code
<uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” />
<uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION” />
Full Code Of AndroidManifest.xml To Enable GPS Location On Webview
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Webview"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
</application>
</manifest>
Step 3 : Set Up the WebView
In the MainActivity class, create a WebView instance and enable JavaScript and geolocation. The geolocation setting will allow the WebView to access the device’s GPS location.
mWebView = findViewById(R.id.webview);
mWebView.setWebViewClient(new WebViewClient()); // to handle URL redirects in the app
mWebView.getSettings().setJavaScriptEnabled(true); // to enable JavaScript on web pages
mWebView.getSettings().setGeolocationEnabled(true); // to enable GPS location on web pages
How To Enable GPS Location On Webview Android Studio?
Step 4: Implement the WebChromeClient
The WebChromeClient class provides methods to handle JavaScript dialogs, geolocation permission requests, and other web-related actions. Override the onGeolocationPermissionsShowPrompt() method to request permission to access the device’s location.
mWebView.setWebChromeClient(new WebChromeClient() {
@Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
} else {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String latitude = String.valueOf(location.getLatitude());
String longitude = String.valueOf(location.getLongitude());
String url = "https://www.example.com?lat=" + latitude + "&long=" + longitude;
mWebView.loadUrl(url);
callback.invoke(origin, true, true);
} else {
callback.invoke(origin, false, false);
}
}
}
@Override
public void onPermissionRequest(PermissionRequest request) {
if (request.getOrigin().toString().startsWith("https://")) {
request.grant(new String[]{Manifest.permission.ACCESS_FINE_LOCATION});
} else {
super.onPermissionRequest(request);
}
}
});
The onGeolocationPermissionsShowPrompt() method is called when the WebView needs to request permission to access the device’s location. Inside this method, we check if the ACCESS_FINE_LOCATION permission has been granted. If not, we request it. If the permission is granted, we get the last known location from the LocationManager and load the web page with the latitude and longitude parameters.
The onPermissionRequest() method is called when the WebView needs to request permission for a specific action. In this case, we check if the request is coming from a secure (https) origin and grant the ACCESS_FINE_LOCATION permission if it is.
Step 5: Check Location Permission and Load the Web Page
Before loading the web page, check if the ACCESS_FINE_LOCATION permission has been granted. If it has, load the web page. If not, request the permission.
// Check if location permission is granted
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Request location permission if not granted
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
} else {
// Load the web page if location permission is granted
mWebView.loadUrl(url);
}
Full Code Of MainActivity.java To Enable GPS Location On Webview
package com.toptools.webview;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.GeolocationPermissions;
import android.webkit.PermissionRequest;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.core.app.ActivityCompat;
public class MainActivity extends AppCompatActivity {
private WebView mWebView;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
String url;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = findViewById(R.id.webview);
mWebView.setWebViewClient(new WebViewClient()); // to handle URL redirects in the app
mWebView.getSettings().setJavaScriptEnabled(true); // to enable JavaScript on web pages
mWebView.getSettings().setGeolocationEnabled(true); // to enable GPS location on web pages
mWebView.setWebChromeClient(new WebChromeClient() {
@Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
} else {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String latitude = String.valueOf(location.getLatitude());
String longitude = String.valueOf(location.getLongitude());
String url = "https://www.example.com?lat=" + latitude + "&long=" + longitude;
mWebView.loadUrl(url);
callback.invoke(origin, true, true);
} else {
callback.invoke(origin, false, false);
}
}
}
@Override
public void onPermissionRequest(PermissionRequest request) {
if (request.getOrigin().toString().startsWith("https://")) {
request.grant(new String[]{Manifest.permission.ACCESS_FINE_LOCATION});
} else {
super.onPermissionRequest(request);
}
}
});
// Check if location permission is granted
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Request location permission if not granted
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
} else {
// Load the web page if location permission is granted
mWebView.loadUrl(url);
}
mWebView.loadUrl("https://www.GOOGLE.com");
}
public class myWebViewclient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
final String urls = url;
if (urls.contains("mailto") || urls.contains("whatsapp") || urls.contains("tel") || urls.contains("sms") || urls.contains("facebook") || urls.contains("truecaller") || urls.contains("")) {
mWebView.stopLoading();
Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.setData(Uri.parse(urls));
startActivity(i);
}
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
}
@Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mWebView.loadUrl(url); // to load the web page after location permission is granted
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
Full Code Of activity_main.xml To Enable GPS Location On Webview
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>