Веб-просмотр карт Google не может найти текущее местоположение, и навигация по открытию приложения карт Google не удалась - PullRequest
0 голосов
/ 14 января 2019

Я создал веб-просмотр карт Google для своего приложения, и он не может получить текущее местоположение, и после того, как я установил пункт назначения и начальное местоположение, навигация не предназначена для карт Google, может кто-нибудь помочь мне решить эту проблему?

package example.asus.com.map;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;

import android.webkit.WebViewClient;
import android.app.Activity;


/**
 * A minimal WebView app with HTML5 geolocation capability
 *
 *  
 */
public class MainActivity extends Activity {

/**
 * WebViewClient subclass loads all hyperlinks in the existing WebView
 */
public class GeoWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // When user clicks a hyperlink, load in the existing WebView
        view.loadUrl(url);
        return true;
    }
}

/**
 * WebChromeClient subclass handles UI-related calls
 * Note: think chrome as in decoration, not the Chrome browser
 */
public class GeoWebChromeClient extends WebChromeClient {
    @Override
    public void onGeolocationPermissionsShowPrompt(String origin,

GeolocationPermissions.Callback callback) {
        // Always grant permission since the app itself requires location
        // permission and the user has therefore already granted it
        callback.invoke(origin, true, false);
    }
}

WebView mWebView;

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mWebView = (WebView) findViewById(R.id.Webview);
    // Brower niceties -- pinch / zoom, follow links in place
    mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    mWebView.setWebViewClient(new GeoWebViewClient());
    // Below required for geolocation
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setGeolocationEnabled(true);
    mWebView.setWebChromeClient(new GeoWebChromeClient());
    // Load google.com
    mWebView.loadUrl("http://www.google.com/maps");

}

@Override
public void onBackPressed() {
    // Pop the browser back stack or exit the activity
    if (mWebView.canGoBack()) {
        mWebView.goBack();
    } else {
        super.onBackPressed();
    }
}
private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, String url) {
        return false;
    }
}
}

Возможность получить текущее местоположение
Возможность навигации по текущему местоположению до пункта назначения

1 Ответ

0 голосов
/ 14 января 2019

Ваш код почти верен: для получения текущего местоположения необходимо настроить WebChromeClient с onGeolocationPermissionsShowPrompt(). Но onGeolocationPermissionsShowPrompt() должно быть более сложным, чтобы разрешить разрешения для геолокации в API 6.0+: он должен запрашивать разрешение во время выполнения, а хост Activity должен обрабатывать ответ в onRequestPermissionsResult(), как описано в this ответ EricRobertBrewer :

Для вашего исходного кода это может быть что-то вроде:

// Geolocation permission request code
private static final int RP_ACCESS_LOCATION = 1001;

// global variables for the origin for permission and interface used by the your application to set the Geolocation permission state for an origin
private String mGeolocationOrigin;
private GeolocationPermissions.Callback mGeolocationCallback;

public class GeoWebChromeClient extends WebChromeClient {
    @Override
    public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
        final String permission = Manifest.permission.ACCESS_FINE_LOCATION;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
            ContextCompat.checkSelfPermission(MainActivity.this, permission) == PackageManager.PERMISSION_GRANTED) {
            // that is you already implement, but it works only
            // we're on SDK < 23 OR user has ALREADY granted permission
            callback.invoke(origin, true, false);
        } else {
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission)) {
                // user has denied this permission before and selected [/] DON'T ASK ME AGAIN
                // TODO Best Practice: show an AlertDialog explaining why the user could allow this permission, then ask again
            } else {
                // store 
                mGeolocationOrigin = origin;
                mGeolocationCallback = callback;
                // ask the user for permissions
                ActivityCompat.requestPermissions(MainActivity.this, new String[] {permission}, RP_ACCESS_LOCATION);
            }
        }
    }
} 

и onRequestPermissionsResult() в этом случае могут быть такими:

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case RP_ACCESS_LOCATION:
            boolean allow = false;
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // user has allowed these permissions
                allow = true;
            }
            if (mGeolocationCallback != null) {
                // use stored callback and origin for allowing Geolocation permission for WebView
                mGeolocationCallback.invoke(mGeolocationOrigin, allow, false);
            }
            break;
    }
}

Также ваше приложение должно было объявить android.permission.ACCESS_FINE_LOCATION разрешение, объявленное AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
...