如何使用ViewPager在片段上放置Google Maps V2


138

我正在尝试在Play商店中使用相同的标签布局。我必须使用androidhive中的片段和viewpager显示选项卡布局。但是,我不能在上面实现google maps v2。我已经在互联网上搜索了几个小时,但是找不到如何使用它的教程。有人可以告诉我如何吗?


3
有趣的是,我不得不回到三年前提出的问题,这样我才能记住如何实现它。
Jeongbebs

Activity和使用Fragment过一次实现之间没有太大区别getChildFragmentManager()
NecipAllef

Answers:


320

通过使用此代码,我们可以在任何ViewPager或Fragment或Activity中的任何位置设置MapView。

在Google for Maps的最新更新中,片段仅支持MapView。MapFragment和SupportMapFragment不起作用。我可能是错的,但这是在尝试实现MapFragment&SupportMapFragment之后看到的内容。

设置布局以在文件中显示地图location_fragment.xml

<?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" >

    <com.google.android.gms.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

现在,我们编码Java类以在文件中显示地图MapViewFragment.java

public class MapViewFragment extends Fragment {

    MapView mMapView;
    private GoogleMap googleMap;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.location_fragment, container, false);

        mMapView = (MapView) rootView.findViewById(R.id.mapView);
        mMapView.onCreate(savedInstanceState);

        mMapView.onResume(); // needed to get the map to display immediately

        try {
            MapsInitializer.initialize(getActivity().getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }

        mMapView.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap mMap) {
                googleMap = mMap;

                // For showing a move to my location button
                googleMap.setMyLocationEnabled(true);

                // For dropping a marker at a point on the Map
                LatLng sydney = new LatLng(-34, 151);
                googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));

                // For zooming automatically to the location of the marker
                CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
                googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            }
        });

        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }
}

最后,您需要通过在Google Cloud Console中注册应用程序来获取应用程序的API密钥。将您的应用注册为本机Android应用。


2
<uses-library android:name="com.google.android.maps" android:required="true" />适用于Maps V1,而不适用于Maps V2。将来会有一些设备没有com.google.android.maps固件库,但是完全能够显示Maps V2地图。在清单中包含此行将阻止您在此类设备上运行,并且对于Maps V2的使用,不需要此行。例如,github.com/commonsguy/cw-omnibus/tree/master/MapsV2上的17个项目没有此<uses-library>元素,并且工作正常。
CommonsWare,2013年

7
我在使用此方法时遇到错误。请帮助PID:com.example.imran.maps.MeFragment.setUpMapIfNeeded(MeFragment.java:115)的com.example.imran.maps.MeFragment.onCreateView的16260 java.lang.NullPointerException (MeFragment.java:72)代码在这里:googleMap =((SupportMapFragment)MainActivity.fragmentManager .findFragmentById(R.id.map))。getMap();
伊姆兰·艾哈迈德

7
我在mMap =((SupportMapFragment)MainActivity.fragmentManager .findFragmentById(R.id.location_map))。getMap();上收到错误消息“ NullPointerException”;
aletede91 2015年

4
示例代码块:mMap =(((SupportMapFragment)MainActivity.fragmentManager .findFragmentById(R.id.location_map))。getMap(); 如果findFragmentById()返回null,将在getMap()中崩溃。
Gunnar Forsgren-Mobimation 2015年

2
是的,这行不通: java.lang.NullPointerException: Attempt to invoke interface method 'void com.google.maps.api.android.lib6.impl.bo.o()' on a null object reference
Peter Weyand '18

146

以下方法对我有用。

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

/**
 * A fragment that launches other parts of the demo application.
 */
public class MapFragment extends Fragment {

MapView mMapView;
private GoogleMap googleMap;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // inflat and return the layout
    View v = inflater.inflate(R.layout.fragment_location_info, container,
            false);
    mMapView = (MapView) v.findViewById(R.id.mapView);
    mMapView.onCreate(savedInstanceState);

    mMapView.onResume();// needed to get the map to display immediately

    try {
        MapsInitializer.initialize(getActivity().getApplicationContext());
    } catch (Exception e) {
        e.printStackTrace();
    }

    googleMap = mMapView.getMap();
    // latitude and longitude
    double latitude = 17.385044;
    double longitude = 78.486671;

    // create marker
    MarkerOptions marker = new MarkerOptions().position(
            new LatLng(latitude, longitude)).title("Hello Maps");

    // Changing marker icon
    marker.icon(BitmapDescriptorFactory
            .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

    // adding marker
    googleMap.addMarker(marker);
    CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(new LatLng(17.385044, 78.486671)).zoom(12).build();
    googleMap.animateCamera(CameraUpdateFactory
            .newCameraPosition(cameraPosition));

    // Perform any camera updates here
    return v;
}

@Override
public void onResume() {
    super.onResume();
    mMapView.onResume();
}

@Override
public void onPause() {
    super.onPause();
    mMapView.onPause();
}

@Override
public void onDestroy() {
    super.onDestroy();
    mMapView.onDestroy();
}

@Override
public void onLowMemory() {
    super.onLowMemory();
    mMapView.onLowMemory();
}
}

fragment_location_info.xml

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

8
你是个天才,你救了我的命。mMapView.onResume(); //得到地图上立即显示需要的是关键
斯特凡

1
我不断收到同样的错误java.lang.NullPointerException: IBitmapDescriptorFactory is not initialized。我以为可以尝试一下。有人可以帮我吗?

@BrandonYang多数民众赞成在真棒..我能够很简单地解决导航抽屉和地图组合...干杯!
Sreehari

@BrandonYang:您知道为什么需要手动为其调用所有生命周期回调mMapView吗?
Christian Aichinger

6
getMap()不推荐使用。请改用getMapAsync和onMapReadyCallback:stackoverflow.com/a/31371953/4549776
jmeinke '16

80

如果要GoogleMap在片段中使用,可以使用以下行:

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

GoogleMap mGoogleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMap();

4
谢谢你的答案!所有其他响应都不适用于最新的支持库
Kamil Nekanowicz 2014年

1
在片段内调用片段是一种好习惯吗?这如何影响应用程序性能和良好的软件设计?
AouledIssa

49

最新资料,getMapAsync而不是已弃用的资料。

1.检查清单

<meta-data android:name="com.google.android.geo.API_KEY" android:value="xxxxxxxxxxxxxxxxxxxxxxxxx"/>

您可以通过在上注册应用程序来获取应用程序的API密钥Google Cloud Console。将您的应用注册为本机Android应用

2.在片段布局.xml中添加FrameLayout(非片段):

                  <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="250dp"
                android:layout_weight="2"
                android:name="com.google.android.gms.maps.SupportMapFragment"
                android:id="@+id/mapwhere" />

或您想要的任何高度

3.在片段中的onCreateView中

    private SupportMapFragment mSupportMapFragment; 

    mSupportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapwhere);
    if (mSupportMapFragment == null) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        mSupportMapFragment = SupportMapFragment.newInstance();
        fragmentTransaction.replace(R.id.mapwhere, mSupportMapFragment).commit();
    }

    if (mSupportMapFragment != null)
    {
        mSupportMapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override public void onMapReady(GoogleMap googleMap) {
                if (googleMap != null) {

                    googleMap.getUiSettings().setAllGesturesEnabled(true);

                      -> marker_latlng // MAKE THIS WHATEVER YOU WANT

                        CameraPosition cameraPosition = new CameraPosition.Builder().target(marker_latlng).zoom(15.0f).build();
                        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
                        googleMap.moveCamera(cameraUpdate);

                }

            }
        });

3
谢谢,节省大量时间,根据今天的最新库更新,这是正确的答案。
山姆

对我来说,它没有用。我花了很多时间注意到,应该使用布局<fragment代替FrameLayout
user3448282 2015年

IMO代码中有一个小但重要的错误。应该有FragmentManagerfragmentManager = getChildFragmentManager(); 添加SupportMapFragment时使用getFragmentManager代替。就像现在的代码一样,总是在调用onCreateView时添加地图片段(这很糟糕,因为它不保持地图状态)。此外,我只在分支mSupportmapFragment == null中调用getMapAsync才能执行一次初始设置!
user1299412

@ user1299412,您可以编辑帖子,我将更新答案。:)
OWADVL 2015年

当我改变了SupportMapFragmentMapFragment活动中,改变FrameLayoutfragment在布局文件,并改变com.google.android.gms.maps.SupportMapFragmentcom.google.android.gms.maps.MapFragment正常工作对我来说。在进行这些更改之前,它不起作用。也许这对其他人有帮助
...。– CodeNinja

10

这是我详细做的:

从这里您可以获取Google Map API密钥

替代和简单的方法

首先登录您的Google帐户并访问Google图书馆,然后选择Google Maps Android API

在android studio默认地图活动中找到依赖项:

compile 'com.google.android.gms:play-services:10.0.1'

将您的密钥放入以下应用程序下的android mainifest文件中

在AndroidMainifest.xml中进行以下更改:

    // required permission
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />


        // google map api key put under/inside <application></application>
        // android:value="YOUR API KEY"
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzasdfasdf645asd4f847sad5f45asdf7845" />

片段代码:

public class MainBranchFragment extends Fragment implements OnMapReadyCallback{

private GoogleMap mMap;
    public MainBranchFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_main_branch, container, false);
        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.main_branch_map);
        mapFragment.getMapAsync(this);
        return view;
    }




     @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            LatLng UCA = new LatLng(-34, 151);
            mMap.addMarker(new MarkerOptions().position(UCA).title("YOUR TITLE")).showInfoWindow();

            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(UCA,17));

        }
    }

在您的片段xml中:

<fragment
                android:id="@+id/main_branch_map"
                android:name="com.google.android.gms.maps.SupportMapFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context="com.googlemap.googlemap.MapsActivity" />

gMapFragment.getMapAsync在getMapAsync上有未解决的引用。这行不通。
Peter Weyand '18

您在活动还是处于碎片状态?
dharmx

这可行!但我不确定在片段中调用片段是否是一种好习惯!请指教
AouledIssa

5

对于在NullPointerException更改Tab中的标签时出现a 的问题,FragmentTabHost您只需将此代码添加到具有的类中TabHost。我的意思是您在其中初始化选项卡的类。这是代码:

/**** Fix for error : Activity has been destroyed, when using Nested tabs 
 * We are actually detaching this tab fragment from the `ChildFragmentManager`
 * so that when this inner tab is viewed back then the fragment is attached again****/

import java.lang.reflect.Field;

@Override
public void onDetach() {
    super.onDetach();
    try {
        Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
        childFragmentManager.setAccessible(true);
        childFragmentManager.set(this, null);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

我应该在“字段”类型上导入什么?有很多可能性。
Jeongbebs 2013年

我应该把你的项目寄给你吗?然后也许告诉我该怎么办?
Jeongbebs

项目已发送到您的电子邮件。
Jeongbebs 2013年

您尚未将google-play-service.jar添加到您的项目中,还需要将project.properties从“ target = android-18”更改为“ target = Google Inc.:Google APIs:18”
arshu

1
此错误已在Android开放源问题跟踪器中跟踪:code.google.com/p/android/issues/detail?id=42601
Kristopher Johnson

4
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" />

有没有办法将地图片段移到另一个片段的后面。菜单片段?它以某种方式刷新并将我的菜单片段发送回去,而不是呆在原处。
sitilge 2015年

您实际上想做什么?
Vaishali Sutariya 2015年

3

当您添加地图时,请使用:

getChildFragmentManager().beginTransaction()
    .replace(R.id.menu_map_container, mapFragment, "f" + shabbatIndex).commit();

代替.add和代替getFragmentManager


1

我只是创建MapActivity并将其膨胀为fragment。MapActivity.java:

package com.example.ahmedsamra.mansouratourguideapp;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_categories);//layout for container
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, new MapFragment())
                .commit();
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng mansoura = new LatLng(31.037933, 31.381523);
        mMap.addMarker(new MarkerOptions().position(mansoura).title("Marker in mansoura"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(mansoura));
    }
}

activity_map.xml:

<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="match_parent"
    tools:context="com.example.ahmedsamra.mansouratourguideapp.MapsActivity" />

MapFragment.java:-

package com.example.ahmedsamra.mansouratourguideapp;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * A simple {@link Fragment} subclass.
 */
public class MapFragment extends Fragment {


    public MapFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.activity_maps,container,false);
        return rootView;
    }

}

什么?不...什么
rexxar

0

NullPointerException当删除片段时,我有一个解决方法DestoryView,只需将代码放在onStop()not中onDestoryView。工作正常!

@Override
public void onStop() {
    super.onStop();
    if (mMap != null) {
        MainActivity.fragmentManager.beginTransaction()
                .remove(MainActivity.fragmentManager.findFragmentById(R.id.location_map)).commit();
        mMap = null;
    }
}

0

根据https://developer.android.com/about/versions/android-4.2.html#NestedFragments的说明,如果您仍想使用Google Maps片段而不是Google Maps片段,则可以通过调用getChildFragmentManager()使用嵌套片段来实现此目的查看您自己的片段内部:

SupportMapFragment mapFragment = new SupportMapFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.content, mapFragment).commit();

其中“内容”是片段中的根布局(最好是FrameLayout)。使用地图片段的优势在于,地图生命周期是由系统自动管理的。

尽管文档说:“当布局包含<fragment>时,您不能将布局充气到一个片段中。只有动态添加到片段中时,才支持嵌套片段。”但是,我已经成功地做到了这一点,并且效果很好。这是我的代码:
在片段的onCreateView()方法中:

View view = inflater.inflate(R.layout.layout_maps, container, false);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(...);

在布局中:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    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="match_parent" />

希望能帮助到你!


0

动态添加地图片段以查看Pager:

如果您要定位API级别12之前的应用程序,请创建一个SupportedMapFragment实例并将其添加到您的视图页面适配器中。

SupportMapFragment supportMapFragment=SupportMapFragment.newInstance();
        supportMapFragment.getMapAsync(this);

API级别12或更高版本支持MapFragment对象

MapFragment mMapFragment=MapFragment.newInstance();
            mMapFragment.getMapAsync(this);

0

这是科特林的方式:

fragment_map.xml你应该有:

<?xml version="1.0" encoding="utf-8"?>
<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" />

在你的MapFragment.kt,你应该有:

    private fun setupMap() {
        (childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?)!!.getMapAsync(this)
    }

呼叫setupMap()onCreateView

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.