在片段中添加Google Maps API V2

我正试图在片段中显示来自Google Maps API V2的地图。 我尝试使用SupportMapFragment,但我无法获得预期的输出。 我也是这个平台的初学者! 我真正想要的只是一种将Google Maps API V2 for Android中的地图放入片段中的方法。 请分享您的想法和参考。

提前致谢 !

  • Android中的speex支持
  • 如何在崩溃后禁用android应用程序自动重启(Android 2.2)
  • NullPointerException(@PhoneWindow:onKeyUpPanel:1002){main}
  • 关于android的Kotlin:找不到主要的合并清单。 导致此错误的原因是什么?
  • java.lang.RuntimeException:无法在LoadedApk.makeApplication 实例化应用程序android.app.Application:java.lang.NullPointerException
  • Android随机字符串生成器
  • 单击通知图标时如何将应用程序置于前面(来自服务)?
  • 用android设备实现Microsoft同步框架
  • 使用SupportMapFragment而不是MapFragment并使用getActivity()

    这是使用SupportMapFragment的基本示例:

     public class MainActivity extends ActionBarActivity implements OnMapReadyCallback{ private SupportMapFragment map; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); map = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); map.getMapAsync(this);//remember getMap() is deprecated! } @Override public void onMapReady(GoogleMap map) { map.moveCamera(CameraUpdateFactory.newLatLngZoom( new LatLng(47.17, 27.5699), 16)); map.addMarker(new MarkerOptions() .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)) .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left .position(new LatLng(47.17, 27.5699))); //Iasi, Romania map.setMyLocationEnabled(true); } } 

    并更改布局中的引用:

      

    这是代码,

     public class YourFragment extends Fragment { // ... static final LatLng HAMBURG = new LatLng(53.558, 9.927); static final LatLng KIEL = new LatLng(53.551, 9.993); private GoogleMap map; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.yourlayout, null, false); map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)) .getMap(); Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG) .title("Hamburg")); Marker kiel = map.addMarker(new MarkerOptions() .position(KIEL) .title("Kiel") .snippet("Kiel is cool") .icon(BitmapDescriptorFactory .fromResource(R.drawable.ic_launcher))); // Move the camera instantly to hamburg with a zoom of 15. map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15)); // Zoom in, animating the camera. map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null); //... return v; } 

    你的布局,

         

    在清单文件中也做一些更改。就像,

      < ?xml version="1.0" encoding="utf-8"?>                     
     public class DemoFragment extends Fragment { MapView mapView; GoogleMap map; LatLng CENTER = null; public LocationManager locationManager; double longitudeDouble; double latitudeDouble; String snippet; String title; Location location; String myAddress; String LocationId; String CityName; String imageURL; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view = inflater .inflate(R.layout.fragment_layout, container, false); mapView = (MapView) view.findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); setMapView(); } private void setMapView() { try { MapsInitializer.initialize(getActivity()); switch (GooglePlayServicesUtil .isGooglePlayServicesAvailable(getActivity())) { case ConnectionResult.SUCCESS: // Toast.makeText(getActivity(), "SUCCESS", Toast.LENGTH_SHORT) // .show(); // Gets to GoogleMap from the MapView and does initialization // stuff if (mapView != null) { locationManager = ((LocationManager) getActivity() .getSystemService(Context.LOCATION_SERVICE)); Boolean localBoolean = Boolean.valueOf(locationManager .isProviderEnabled("network")); if (localBoolean.booleanValue()) { CENTER = new LatLng(latitude, longitude); } else { } map = mapView.getMap(); if (map == null) { Log.d("", "Map Fragment Not Found or no Map in it!!"); } map.clear(); try { map.addMarker(new MarkerOptions().position(CENTER) .title(CityName).snippet("")); } catch (Exception e) { e.printStackTrace(); } map.setIndoorEnabled(true); map.setMyLocationEnabled(true); map.moveCamera(CameraUpdateFactory.zoomTo(5)); if (CENTER != null) { map.animateCamera( CameraUpdateFactory.newLatLng(CENTER), 1750, null); } // add circle CircleOptions circle = new CircleOptions(); circle.center(CENTER).fillColor(Color.BLUE).radius(10); map.addCircle(circle); map.setMapType(GoogleMap.MAP_TYPE_NORMAL); } break; case ConnectionResult.SERVICE_MISSING: break; case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED: break; default: } } catch (Exception e) { } } 

    在fragment_layout中

      

    2014年10月24日更新这一切都错了。 你不应该在片段中有片段。 相反,您应该扩展SupportMapFragment。 有关详细信息,请参阅此stackoverflowpost: https : //stackoverflow.com/a/19815266/568197

    这是我的onDestroyView()

     public void onDestroyView() { super.onDestroyView(); if (mMap != null) { getFragmentManager() .beginTransaction() .remove(getFragmentManager().findFragmentById(R.id.map)) .commit(); } } 

    除了上面的答案,我还必须在我的清单上加上以下几行

       

    我还更改了布局以使用SupportMapFragment而不是MapFragment

      

    对于所有面临问题的朋友: –

    java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap com.google.android.gms.maps.SupportMapFragment.getMap()

    请尝试使用代码集成GoogleMap

     FragmentManager fm = getChildFragmentManager(); googleMap = ((SupportMapFragment)fm.findFragmentById(R.id.googleMap)).getMap(); 

    这是我的代码。

    在谷歌地图concole中创建项目并生成API密钥。

    然后将依赖项添加到build.gradle(应用程序级别)。

     compile 'com.google.android.gms:play-services-maps:10.2.1' compile 'com.google.android.gms:play-services-location:10.2.1' compile 'com.google.android.gms:play-services-places:10.2.1' 

    记得在Android.manifest中添加权限

              

    创建activity_main.xml

        

    没有什么可以从MainActivity.class调用

    创建fragment_location.xml

        

    创建FragmentLocation.class

     public class FragmentLocation extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { public static final String TAG = FragmentLocation.class.getSimpleName(); public static final int REQUEST_CODE_FOR_PERMISSIONS = 1; GoogleApiClient mGoogleApiClient; LatLng mLatLng; GoogleMap mGoogleMap; Marker mCurrLocationMarker; private LinearLayout linearMap; Location mLastLocation; LocationManager locationManager; boolean statusOfGPS; private Dialog mDialogGPS; View view; LocationRequest mLocationRequest; SupportMapFragment mFragment; FragmentManager fragmentManager; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view=inflater.inflate(R.layout.fragment_location,container,false); fragmentManager=getChildFragmentManager(); mFragment = (SupportMapFragment)fragmentManager.findFragmentById(R.id.map); mFragment.getMapAsync(this); if (!isGooglePlayServicesAvailable()) { Toast.makeText(getActivity(), "play services not available", Toast.LENGTH_SHORT).show(); } locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); return view; } @Override public void onConnected(Bundle bundle) { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(1000); //5 seconds mLocationRequest.setFastestInterval(2000); //3 seconds mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); } } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } @Override public void onLocationChanged(Location location) { mLastLocation = location; if (mCurrLocationMarker != null) { mCurrLocationMarker.remove(); } mLatLng = new LatLng(location.getLatitude(), location.getLongitude()); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(mLatLng); markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)); mCurrLocationMarker = mGoogleMap.addMarker(markerOptions); mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(mLatLng)); // Zoom in the Google Map mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); } @Override public void onMapReady(GoogleMap googleMap) { mGoogleMap = googleMap; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (getActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED && getActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { buildGoogleApiClient(); mGoogleMap.setMyLocationEnabled(true); } else { requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION , Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_FOR_PERMISSIONS); } } else { buildGoogleApiClient(); mGoogleMap.setMyLocationEnabled(true); } //show dialog when click on location top-right side located on map. mGoogleMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() { @Override public boolean onMyLocationButtonClick() { statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); if (!statusOfGPS) { turnOnGps(); } else { getCurrentLocation(mLastLocation); } return false; } }); } private boolean isGooglePlayServicesAvailable() { int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity()); if (ConnectionResult.SUCCESS == status) { return true; } else { GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show(); return false; } } @RequiresApi(api = Build.VERSION_CODES.M) @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case REQUEST_CODE_FOR_PERMISSIONS: if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (getActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED && getActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if (mGoogleApiClient == null) { buildGoogleApiClient(); } mGoogleMap.setMyLocationEnabled(true); } } else { if (!(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_COARSE_LOCATION)) && (!(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)))) { Snackbar snackbar = Snackbar.make(linearMap, "Never asked" , Snackbar.LENGTH_INDEFINITE); snackbar.setAction("Allow", new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(); intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null); intent.setData(uri); startActivity(intent); } }); snackbar.show(); } } break; } } private void getCurrentLocation(Location location) { mLastLocation = location; if (mCurrLocationMarker != null) { mCurrLocationMarker.remove(); } if (locationManager != null) { if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mLastLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);//getting last location } if (mLastLocation != null) { if (mGoogleMap != null) { Log.d("activity", "LOC by Network"); mLatLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(mLatLng); markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)); mCurrLocationMarker = mGoogleMap.addMarker(markerOptions); mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(mLatLng)); mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); } } } } private void turnOnGps() { if (mGoogleMap != null) { mGoogleMap.clear(); } statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);//getting status of gps whether gps is on or off. mDialogGPS = new Dialog(getActivity(), R.style.MyDialogTheme); mDialogGPS.requestWindowFeature(Window.FEATURE_NO_TITLE); mDialogGPS.setContentView(R.layout.dialog_turnongps); TextView txtCancel = (TextView) mDialogGPS.findViewById(R.id.txtCancel); TextView txtOK = (TextView) mDialogGPS.findViewById(R.id.txtSetting); ImageView imgLocation = (ImageView) mDialogGPS.findViewById(R.id.imgLocation); imgLocation.setImageResource(R.drawable.ic_location_my); txtCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mDialogGPS.dismiss(); //finish(); if (!statusOfGPS) { getCurrentLocationByDefault(); } else { getCurrentLocation(mLastLocation); } } }); txtOK.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //It is use to redirect to setting->location to turn on gps when press ok. startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); mDialogGPS.dismiss(); if (!statusOfGPS) { getCurrentLocationByDefault(); } else { getCurrentLocation(mLastLocation); } } }); mDialogGPS.show(); } private void getCurrentLocationByDefault() { if (mCurrLocationMarker != null) { mCurrLocationMarker.remove(); } if (mGoogleMap != null) { LatLng xFrom1 = new LatLng(0.0, 0.0); mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(xFrom1, (float) 0.0)); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(xFrom1); markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_taxi)); mCurrLocationMarker = mGoogleMap.addMarker(markerOptions); } else { Log.i("MainActivity", "getCurrentLocationByDefault else"); } } @Override public void onResume() { super.onResume(); statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); if (mDialogGPS != null) { if (mDialogGPS.isShowing()) { mDialogGPS.dismiss(); } } if (!statusOfGPS) { turnOnGps(); } else { getCurrentLocation(mLastLocation); } } protected synchronized void buildGoogleApiClient() { if (mGoogleApiClient != null) { mGoogleApiClient = null; } mGoogleApiClient = new GoogleApiClient.Builder(getActivity()) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); mGoogleApiClient.connect(); } } 

    创建dailog_gps.xml

                     

    希望对你有帮助 :-)

    我有同样的问题,我使用这个代码,但我仍然得到这个错误:无法实例化片段com.google.android.gsm.SupportMapFragment:确保类名存在,是公共的,并且具有空构造或公共

    我从这里解决了它: 如何使用ViewPager将Google Maps V2放在片段上

    如果你正在使用android studio创建google mapsactivity它的默认地图片段并生成你的地图API KEY并做你的东西……

    SupportMapFragment mapFragment =(SupportMapFragment)getSupportFragmentManager()。findFragmentById(R.id.map); mapFragment.getMapAsync(本);

    和我们的覆盖方法

    public void onMapReady(GoogleMap googleMap){

      mMap = googleMap; LatLng map = new LatLng(lat, lon); mMap.addMarker(new MarkerOptions().position(map).title("your title")); mMap.animateCamera(CameraUpdateFactory.newLatLng(map)); mMap.setMapType(GoogleMap.MAP_TYPE_NONE); } 

    这个例子是从android studio的自动生成代码构建的,你不需要在地图活动中改变任何东西,只需要布局文件中的上下文来匹配你的地图Activity

     < ?xml version="1.0" encoding="utf-8"?>       

    在Google Maps Android API v2.0下使用Fragment中的MapView

    公共类MapFragment扩展Fragment {

     MapView m; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // inflat and return the layout View v = inflater.inflate(R.layout.map_fragment, container, false); m = (MapView) v.findViewById(R.id.mapView); m.onCreate(savedInstanceState); return v; } @Override public void onResume() { super.onResume(); m.onResume(); } @Override public void onPause() { super.onPause(); m.onPause(); } @Override public void onDestroy() { super.onDestroy(); m.onDestroy(); } @Override public void onLowMemory() { super.onLowMemory(); m.onLowMemory(); } 

    }

    http://ucla.jamesyxu.com/?p=287