【问题标题】:How to use Google Maps in a fragment如何在片段中使用谷歌地图
【发布时间】:2016-05-24 04:49:05
【问题描述】:

我想把这个类放在一个片段中,我怎样才能把它变成一个片段类?

public class MapsActivity extends FragmentActivity {

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        setUpMapIfNeeded();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    } 

我需要这些方法在我的片段中工作。但我无法通过按钮开车

    public void onSearch(View view) {
        EditText location_tf = (EditText) findViewById(R.id.TFaddress);
        String location = location_tf.getText().toString();
        List<Address> addressList = null;
        if (location != null || !location.equals("")) {
            Geocoder geocoder = new Geocoder(this);
            try {
                addressList = geocoder.getFromLocationName(location, 1);


            } catch (IOException e) {
                e.printStackTrace();
            }
                Address address = addressList.get(0);
            LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
            mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
            mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            }
    }
        public void onZoom(View view) {
        if (view.getId() == R.id.Bzoomin) {
            mMap.animateCamera(CameraUpdateFactory.zoomIn());
        }
        if (view.getId() == R.id.Bzoomout) {
            mMap.animateCamera(CameraUpdateFactory.zoomOut());
        }
    }

    public void changeType(View view) {
        if (mMap.getMapType() == GoogleMap.MAP_TYPE_NORMAL) {
            mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        } else
            mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    }

    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

所有这些动作都通过“onClick”连接到布局

    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mMap.setMyLocationEnabled(true);


    }
}

【问题讨论】:

    标签: android maps fragment


    【解决方案1】:

    对我有用的是这个

    childFragmentManager.fragments[0] as SupportMapFragment?
    

    让我解释一下:我有一个片段:地图片段,里面还有一个带有地图的片段,所以它是他唯一的孩子。请注意,这不是最佳做法,但我现在可以工作

    class MapFragment : Fragment(), OnMapReadyCallback {
    
    private lateinit var mMap: GoogleMap
    
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val rootView: View = inflater.inflate(R.layout.fragment_map, container, false)
        val mapFragment =
            childFragmentManager.fragments[0] as SupportMapFragment?
        mapFragment!!.getMapAsync(this)
        return rootView
    }
    
    override fun onMapReady(googleMap: GoogleMap?) {
        mMap = googleMap!!
        // Add a marker in Sydney and move the camera
        val sydney = LatLng(-34.0, 151.0)
        mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
     }
    }
    

    我的片段的 xml 是

         <?xml version="1.0" encoding="utf-8"?>
         <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ui.MainActivity">
        <fragment
            android:id="@+id/map"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            class="com.google.android.gms.maps.SupportMapFragment" />
    </FrameLayout>
    

    【讨论】:

      【解决方案2】:

      片段类应该是这样的......

      public MyMapFragment extends Fragment{
      
       private GoogleMap map;
          public GoogleApiClient mGoogleApiClient;
          private LocationRequest locationRequest;
          private Location myLocation;
      
      @Override
          public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              mGoogleApiClient = new GoogleApiClient.Builder(getActivity()).addConnectionCallbacks(this)
                      .addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
          }
      
      @Override
          public void onActivityCreated(Bundle savedInstance) {
              super.onActivityCreated(savedInstance);
      
              map = ((MapFragment) act.getFragmentManager()
                      .findFragmentById(R.id.map)).getMap();
              map.getUiSettings().setRotateGesturesEnabled(false);
              map.getUiSettings().setZoomControlsEnabled(false);
              map.setTrafficEnabled(true);
              map.setOnMarkerDragListener(dragListener);
              map.setOnMapLongClickListener(longClickListener);
      
          }
      
       @Override
          public void onStart() {
              super.onStart();
              if (mGoogleApiClient != null)
                  mGoogleApiClient.connect();
          }
      
       private void showCurrentLocation(Location location) {
              if (map.getCameraPosition().zoom < MAP_ZOOM_LEVEl) {
                  map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
                          location.getLatitude(), location.getLongitude()), 12));
              }
              CameraPosition cameraPosition = new CameraPosition(new LatLng(
                      location.getLatitude(), location.getLongitude()),
                      map.getCameraPosition().zoom, 45, 360);
              map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
      
          }
      
      @Override
          public void onConnected(@Nullable Bundle bundle) {
      
              if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                  if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                          && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                      return;
                  }
              }
              myLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
              if (myLocation != null) {
                  showCurrentLocation(myLocation);
                  return;
              }
              if ("Check for GPS Status")
                 Show the error if not enabled
              LocationServices.FusedLocationApi.requestLocationUpdates(
                      mGoogleApiClient, locationRequest, new LocationListener() {
                          @Override
                          public void onLocationChanged(Location location) {
                              if (location == null)
                                  return;
                              myLocation = location;
                              showCurrentLocation(location);
                          }
                      });
      
      
          }
      
          protected void createLocationRequest() {
              locationRequest = new LocationRequest();
              locationRequest.setFastestInterval(FASTEST_INTERVAL);
              locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
          }
      
      @Override
          public void onStop() {
              super.onStop();
              if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
                  mGoogleApiClient.disconnect();
          }
      
          @Override
          public void onDestroyView() {
              super.onDestroyView();
      
              MapFragment mapFragment = (MapFragment) getActivity()
                      .getFragmentManager().findFragmentById(R.id.map);
              if (mapFragment != null)
                  getActivity().getFragmentManager().beginTransaction()
                          .remove(mapFragment).commit();
          }
      }
      

      该片段的布局

      <?xml version="1.0" encoding="utf-8"?>
      <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent" >
      
          <fragment
              android:id="@+id/map"
              android:name="com.google.android.gms.maps.MapFragment"
              android:layout_width="match_parent"
              android:layout_height="match_parent" />
      
      
      
      </RelativeLayout>
      

      【讨论】:

      • 它对我有用,但我如何实现我的 onSeach 方法 onZoom 和 changeType ?
      【解决方案3】:

      在我的项目中,地图是通过以下方式实现的:

      No meu projeto em implementei o Maps da seguindo maneira:

      public class MainFragment extends Fragment implements OnMapReadyCallback {
      
      
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          return inflater.inflate(R.layout.fragment_main, container, false);
      }
      
      @Override
      public void onViewCreated(View view, Bundle savedInstanceState) {
          super.onViewCreated(view, savedInstanceState);
      
          MapFragment fragment = (MapFragment) getChildFragmentManager().findFragmentById(R.id.map);
          fragment.getMapAsync(this);
      } }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-21
        • 2018-12-06
        • 2021-09-08
        • 1970-01-01
        相关资源
        最近更新 更多