【问题标题】:android using fragment and displaying mapandroid使用片段和显示地图
【发布时间】:2017-01-14 17:37:42
【问题描述】:

我有以下片段来显示谷歌地图中的位置。 1) 好像我用了

mwebView.loadUrl("https://www.google.com");

谷歌页面包含在我的片段中。注意汉堡菜单

2) 但如果我使用 goole 地图位置,例如:

mwebView.loadUrl("https://www.google.com/maps/place/Pentecostals+of+Alexandria/@31.3069108,-92.4769955,17z/data=!4m5!3m4!1s0x0:0x2ced09e8ff5c3dbf!8m2!3d31.3069105!4d-92.4748012");

我的应用程序菜单(缺少汉堡包)谷歌地图汉堡包在那里,但我的应用程序菜单不见了。

下面是代码:我想要应用程序汉堡菜单,这样我就可以返回菜单项.....帮助

公共类 find_us 扩展片段 {

public find_us()
{
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    commonfunc.myprint("#####_____find_us_onCreateView ");

    View rootView = inflater.inflate(life.poa.webcastman.poa1.R.layout.fragment_whats_hot, container, false);


    WebView mwebView = (WebView) rootView.findViewById(R.id.myWebView);
    WebSettings webSettings = mwebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    //improve webView performance
    mwebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    mwebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    mwebView.getSettings().setAppCacheEnabled(true);
    mwebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    webSettings.setDomStorageEnabled(true);
    webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
    webSettings.setUseWideViewPort(true);
    webSettings.setSavePassword(true);
    webSettings.setSaveFormData(true);
    webSettings.setEnableSmoothTransition(true);

    mwebView.getSettings().setJavaScriptEnabled(true);

    //mwebView.loadUrl("https://www.google.com");
    mwebView.loadUrl("https://www.google.com/maps/place/Pentecostals+of+Alexandria/@31.3069108,-92.4769955,17z/data=!4m5!3m4!1s0x0:0x2ced09e8ff5c3dbf!8m2!3d31.3069105!4d-92.4748012");

    //force links open in webview only --- This was commented in archive ???
    //mwebView.setWebViewClient(new MyWebviewClient());
    commonfunc.myprint("webview0");
    return rootView;

【问题讨论】:

  • 你为什么使用网络视图?如果您在片段中使用谷歌地图 API 会更好
  • 似乎无法让 api 工作。以上似乎有效,但我失去了我的汉堡菜单。所有其他访问网页,保留应用菜单。
  • 好吧,我尝试向您展示如何在片段中使用谷歌地图 API,如果不是您想要的,请使用片段布局更新您的问题

标签: android google-maps android-fragments


【解决方案1】:

嗯,对我来说,在 web 视图中使用谷歌地图并不是最好的主意(除非是你的应用程序的要求)

如果你使用谷歌地图 API 会更好。我将向您展示的代码用于在片段中使用它。实际上,我正在我正在开发的当前应用程序中使用它(并且运行良好:D)我希望这对您有帮助,如果出现问题,请告诉我

fragment_map_layout.xml

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/linearLayout" />

现在在您的 MapFragment

public class MapFragment extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    private GoogleMap mGoogleMap;
    private GoogleApiClient mGoogleApiClient;

    private static final int MY_LOCATION_PERMISSION = 100;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_map, container, false);
        createGoogleClient();

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    public void onStop() {
        super.onStop();
        try {
            mGoogleApiClient.disconnect();
        }catch (Exception e){
            Log.wtf("onStop: ", "error " + e.getMessage() );
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        setupUI();
    }
   // remember since Android 6 we have to ask for permissions to the user: this is the callback
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_LOCATION_PERMISSION)
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                // TODO: your code here
            }
    }
// Here I setup the map and call getMapAsync(); method
    private void setupUI(){
        SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
// here I init the GoogleApiClient that help me to get the current location and set the callback
    private void createGoogleClient(){
        if (mGoogleApiClient == null){
            mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
            mGoogleApiClient.connect();
        }
    }

// this method is used to ask for permissions in run time, the validations here is only to know the current device Android version if is > Android 6 ask for permissions 
        @TargetApi(Build.VERSION_CODES.M)
        private boolean findLocation() {
            if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.M) || getActivity().checkSelfPermission(ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                mGoogleMap.setMyLocationEnabled(true);
                mGoogleMap.clear();

                Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

                setCurrentLocation(location);

            } else if (shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION)) {
                Toast.makeText(getActivity(), "message for the user", Toast.LENGTH_LONG).show();

            } else {
                requestPermissions(new String[]{ACCESS_FINE_LOCATION}, MY_LOCATION_PERMISSION);
            }

            return false;
        }

// set the current location in the google map
        private void setCurrentLocation(Location location) {
            if (location != null) {
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17);
                mGoogleMap.animateCamera(cameraUpdate);

            }else
                mGoogleApiClient.reconnect();
        }

        private boolean isGpsEnabled() {
            LocationManager lm = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);;
            boolean isEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);

            if (!isEnabled) {
                android.app.AlertDialog.Builder dialog = new android.app.AlertDialog.Builder(getActivity())
                        .setMessage("Please, turn up your GPS")
                        .setPositiveButton("Open settings", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                                Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivity(myIntent);
                            }
                        })
                        .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                                //finish();
                                Toast.makeText(getActivity().getApplicationContext(), "Es necesario que habilites tu GPS", Toast.LENGTH_SHORT).show();
                            }
                        });
                dialog.show();

            }

            return isEnabled;
        }

        @Override
        public void onMapReady(GoogleMap googleMap) {
            mGoogleMap = googleMap;
            mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(19.42499, -99.18644)));
        }

        @Override
        public void onConnected(@Nullable Bundle bundle) {
            if (isGpsEnabled())
                findLocation();
        }

        @Override
        public void onConnectionSuspended(int i) {
            // TODO: your code here
        }

        @Override
        public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
            // TODO: your code here
        }

    }

不要忘记在您的buil.gradle 应用中设置compile 'com.google.android.gms:play-services-maps:10.0.1'

【讨论】:

    猜你喜欢
    • 2015-11-27
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 2018-04-28
    • 1970-01-01
    相关资源
    最近更新 更多