2017-01-14 2 views
0

У меня есть следующий фрагмент для отображения местоположения на картах google. 1) Кажется, что я используюандроид с использованием фрагмента и отображения карты

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

Страница google содержится в моем фрагменте. Обратите внимание на меню гамбургер www.google.com with the hamburger menu ..good

2), но если я использую Гул местоположение на карте Ex:

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");

Мое приложение меню (гамбургер отсутствует) В Google карте гамбургер есть, но мое меню приложения ушло.

A google location , the hamburger menu is missing

Ниже приведен код: Я хочу, чтобы иметь меню приложения гамбургер, так что я могу вернуться к пунктам меню ..... помощь

общественного класса 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; 
+0

Почему вы используете веб-просмотр? лучше, если вы используете API-интерфейс google map в своем фрагменте. – Robert

+0

Не похоже, чтобы api работал. Выше, кажется, работает, но я теряю меню гамбургеров. При любом доступе к веб-страницам сохраняйте меню приложения. – user7236439

+0

Ну, я попытался показать вам, как использовать API-интерфейс google в фрагменте, если это не то, что вы ищете, обновите свой вопрос с помощью макета фрагмента – Robert

ответ

0

Ну, для меня, используя карты Google в WebView не лучшая идея (если не быть требованием вашего приложения)

лучше, если вы используйте API-интерфейс google. Код, который я покажу вам, предназначен для использования в фрагменте. На самом деле я работать с этим в текущем приложении, которое я занимаюсь разработкой (и это работает отлично: D) Я надеюсь, что это будет helpfuly для вас, дайте мне знать, если что-то становится не так

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 
     } 

    } 

Не забудьте установить compile 'com.google.android.gms:play-services-maps:10.0.1' в вашем buil.gradle app

Смежные вопросы