web-dev-qa-db-ja.com

Google Maps API V2をフラグメントに追加します

Google Maps API V2の地図を断片的に表示しようとしています。 SupportMapFragmentを試しましたが、期待した出力を得ることができません。また、私はこのプラットフォームの初心者です!私が本当に欲しいのは、Google Maps API V2からAndroidの断片にマップを配置する方法です。アイデアや参考文献を共有してください。

前もって感謝します !

24

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

レイアウトの参照を変更します。

<fragment
        Android:id="@+id/map"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent"
        class="com.google.Android.gms.maps.SupportMapFragment" />
2
Jorgesys

コードは次のとおりです。

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;
    }

あなたのレイアウト、

 <RelativeLayout 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=".MainActivity" >

    <fragment
        Android:id="@+id/map"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent"
        class="com.google.Android.gms.maps.SupportMapFragment" />

</RelativeLayout>

マニフェストファイルにも変更を加えます。

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:Android="http://schemas.Android.com/apk/res/Android"
    package="com.myapp.Android.locationapi.maps"
    Android:versionCode="1"
    Android:versionName="1.0" >

    <uses-sdk
        Android:minSdkVersion="17"
        Android:targetSdkVersion="17" />

    <permission
        Android:name="com.myapp.Android.locationapi.maps.permission.MAPS_RECEIVE"
        Android:protectionLevel="signature" />

    <uses-feature
        Android:glEsVersion="0x00020000"
        Android:required="true" />

    <uses-permission Android:name="com.myapp.Android.locationapi.maps.permission.MAPS_RECEIVE" />
    <uses-permission Android:name="Android.permission.INTERNET" />
    <uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission Android:name="com.google.Android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission Android:name="Android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission Android:name="Android.permission.ACCESS_FINE_LOCATION" />

    <application
        Android:allowBackup="true"
        Android:icon="@drawable/ic_launcher"
        Android:label="@string/app_name"
        Android:theme="@style/AppTheme" >
        <activity
            Android:name="com.myapp.Android.locationapi.maps.MainActivity"
            Android:label="@string/app_name" >
            <intent-filter>
                <action Android:name="Android.intent.action.MAIN" />

                <category Android:name="Android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            Android:name="com.google.Android.maps.v2.API_KEY"
            Android:value="your_apikey" />
    </application>

</manifest> 
32
Basim Sherif
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で

<com.google.Android.gms.maps.MapView
                Android:id="@+id/mapView"
                Android:layout_width="match_parent"
                Android:layout_height="160dp"                    
                Android:layout_marginRight="10dp" />
8

2014年10月24日更新これはすべて間違っています。フラグメントにフラグメントを含めるべきではありません。むしろ、SupportMapFragmentを拡張する必要があります。詳細については、このstackoverflowの投稿を参照してください: https://stackoverflow.com/a/19815266/568197

ここに私のonDestroyView()があります

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

上記の答えに加えて、マニフェストに次の行も追加する必要がありました

<!-- inside <aplication> tag -->    
<meta-data
            Android:name="com.google.Android.gms.version"
            Android:value="@integer/google_play_services_version" />

また、SupportMapFragmentの代わりにMapFragmentを使用するようにレイアウトを変更しました

<fragment
        Android:id="@+id/map"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent"
        class="com.google.Android.gms.maps.SupportMapFragment" />
3

これが私のコードです。

Googleマップコンソールでプロジェクトを作成し、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に許可を追加することを忘れないでください

<uses-permission Android:name="Android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission Android:name="Android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission Android:name="Android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission Android:name="Android.permission.INTERNET" />
    <uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission Android:name="Android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission Android:name="com.google.Android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission Android:name="Android.permission.ACCESS_WIFI_STATE" />
    <uses-feature Android:name="Android.hardware.location.gps" Android:required="true"/>

activity_main.xmlを作成します

<FrameLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    xmlns:tools="http://schemas.Android.com/tools"
    Android:id="@+id/container"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="MergeRootFrame">

    <fragment
        class="com.googlelocationmapdemo.FragmentLocation"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent" />
</FrameLayout>

MainActivity.classから呼び出すものはありません

Fragment_location.xmlを作成します

<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:id="@+id/linearMap"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent">

    <fragment xmlns:Android="http://schemas.Android.com/apk/res/Android"
        Android:id="@+id/map"
        class="com.google.Android.gms.maps.SupportMapFragment"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent" />
</LinearLayout>

作成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を作成します

<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:layout_width="match_parent"
    Android:layout_height="wrap_content"
    Android:padding="20dp"
    Android:orientation="vertical">


    <LinearLayout

        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:orientation="horizontal">

        <TextView
            Android:id="@+id/txtPhoneNumber"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:text="Use Location?"
            Android:textColor="@Android:color/black"
          Android:textSize="16sp"
            />

    </LinearLayout>

    <LinearLayout
        Android:layout_marginTop="15dp"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:orientation="horizontal">

        <TextView
            Android:layout_width="0dp"
            Android:layout_height="wrap_content"
            Android:layout_weight="1"
            Android:text="This app wants to change your \ndevice settings:"
            Android:textSize="14sp" />

    </LinearLayout>

    <LinearLayout
        Android:layout_marginTop="10dp"
        Android:weightSum="2"
        Android:gravity="center"
        Android:orientation="horizontal"
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content">

        <ImageView
            Android:id="@+id/imgLocation"
            Android:layout_weight="1"
            Android:layout_gravity="top"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content" />

        <TextView
            Android:layout_weight="1"
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content"
            Android:text="Use GPS, Wi-Fi and mobile \nnetwork for location"
            Android:layout_marginLeft="20dp"
            Android:textSize="12sp" />

    </LinearLayout>

    <LinearLayout
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:layout_gravity="right"
        Android:orientation="horizontal"
        Android:layout_marginTop="20dp">

        <TextView
            Android:id="@+id/txtCancel"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:text="NO"
            Android:layout_marginRight="30dp"
            Android:textSize="16sp" />

        <TextView
            Android:id="@+id/txtSetting"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:text="YES"
            Android:layout_marginRight="30dp"
            Android:textSize="16sp" />

    </LinearLayout>
</LinearLayout>

これがあなたを助けることを願っています:-)

1
Firdosh

問題に直面しているすべての友人のために:-

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();
1
Harpreet

Google MapsのFragment内でMapViewを使用するAndroid API v2.0

パブリッククラスMapFragment extends 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

0
Sanjeev Kumar

私は同じ問題を抱えていますが、このコードを使用しますが、まだこのエラーが発生します:フラグメントcom.google.Android.gsm.SupportMapFragmentをインスタンス化できません:クラス名が存在し、パブリックであり、空のコンストラクトがあることを確認するか、パブリック

私はここからそれを解決しました: ViewPagerを使用してGoogle Maps V2をフラグメントに配置する方法

0
user3579994

この例は、Android studio、マップアクティビティでは何も変更する必要はありません。マップアクティビティに一致するレイアウトファイルのコンテキストのみを変更する必要はありません。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:orientation="vertical"
    Android:layout_width="fill_parent"
    Android:layout_height="fill_parent"
    Android:weightSum="1">

<fragment xmlns:Android="http://schemas.Android.com/apk/res/Android"
xmlns:map="http://schemas.Android.com/apk/res-auto"
xmlns:tools="http://schemas.Android.com/tools"
Android:id="@+id/map"
Android:name="com.google.Android.gms.maps.SupportMapFragment"
Android:layout_width="match_parent"
Android:layout_height="300dp"
tools:context="com.gearwell.app.gpsmaps02.Gpsenmapa"

/>

<LinearLayout
    Android:id="@+id/layButtonH"
    Android:layout_height="150dp"
    Android:layout_marginTop="50dp"
    Android:layout_width="fill_parent"
    Android:gravity="center"
    Android:layout_weight="0.15">
    <Button
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:text="Obtener Ubicacion"
        Android:id="@+id/btnLocation"
        Android:onClick="onClick"/>
</LinearLayout>
</LinearLayout>

Android studioを使用している場合、Google MapsActivityのデフォルトのマップフラグメントを作成し、マップAPIキーを生成して作業を行います......

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

そしてオーバーライドメソッド

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

}