如何使用getMapAsync在自己的Android应用程序中显示谷歌地图

时间:2016-04-07 06:45:31

标签: android

我想在我自己的Android应用程序中显示谷歌地图...我使用getMapAsync()在manifest.im中使用谷歌地图api键。但它无法正常工作.. 代码在下面是否有我做过的任何错误。请帮助我.. 谢谢......

这里是xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >

<fragment 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"
          android:id="@+id/map"
          tools:context=".ClinicMap"
          class="com.google.android.gms.maps.SupportMapFragment"
          android:apiKey="AIzaSyCbtSjGcG1g2u9H-hfuO6Tx7F442ZndDb4"/>

这是我的主要活动

public class ClinicMap extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;

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


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

 //        MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
 //        mapFragment.getMapAsync(this);
}

@TargetApi(Build.VERSION_CODES.M)
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Mumbai, India, and move the camera.
    LatLng mumbai = new LatLng(19.0128, 72.8246);
    if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    public void requestPermissions(@NonNull String[] permissions, int requestCode)
        // 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 Activity#requestPermissions for more details.
        return;
    }
    mMap.setMyLocationEnabled(true);
    //mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(mumbai));
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mumbai, 4));
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    mMap.addMarker(new MarkerOptions()
            .title("mumbai")
            .snippet("The most populous city in India.")
            .position(mumbai));
    }
 }

当我使用MapFragment时出现错误&#34;尝试调用虚拟方法&#39; void com.google.android.gms.maps.MapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)&#39;在null对象引用&#34;

当我使用SupportMapFragment时 output will be like these

1 个答案:

答案 0 :(得分:0)

您需要将您的API密钥放在Manifest.xml中而不是布局文件中,如果密钥不在清单文件中,您将无法访问地图服务,并且您的片段将不会显示任何内容。

转到您的清单,检查是否添加了以下行。

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

和INSIDE <application>标记:

<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

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

此外,您需要检查mapFragment对象是否已正确创建,通常我使用此代码块来确保我没有将空引用传递给getMapAsync()。

fragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_fragment);
        if(fragment == null){
            FragmentManager manager = getFragmentManager();
            fragment =SupportMapFragment.newInstance();
            manager.beginTransaction().replace(R.id.map_fragment, fragment).commit();

        }
        if (fragment != null){
            fragment.getMapAsync(this);
        }

我在一个简单的片段中使用过它,你有一个FragmentActivity,所以你可能需要做一些小修正以适应你的情况。

编辑:

我注意到你的类扩展了FragmentActivity,我编写的代码与扩展Fragment的类一起工作。 在我看来,我有两个可能的解决方案:

  1. 创建FragmentActivity和另一个类extends Fragmentimplements OnMapReadyCallback,您可以在其中创建和操作地图。

  2. 创建一个简单的活动,在其layout.xml中创建一个片段并实例化地图。 在这种情况下,你应该有这样的东西:

  3. MAP_LAYOUT.xml:

    <FrameLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">
    
        <fragment
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/map"
            tools:context=".MainActivity"
            android:name="com.google.android.gms.maps.SupportMapFragment" />
    
    </FrameLayout>
    

    ACTIVITY.java:

    我只会写出OnCreate()SetUpMapIfYouNeed()SetUpMap()的详细信息,而不是全班。

    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.map_activity);
    
            Bundle bundle = new Bundle(getIntent().getExtras());
            this.title = bundle.getString("name");
            setUpMapIfNeeded();
            //Other lines of code
            //...
            //...
            }
    
    
    /**
         * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
         * installed) and the map has not already been instantiated.. This will ensure that we only ever
         * call {@link #setUpMap()} once when {@link #mMap} is not null.
         * <p/>
         * If it isn't installed {@link SupportMapFragment} (and
         * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
         * install/update the Google Play services APK on their device.
         * <p/>
         * A user can return to this FragmentActivity after following the prompt and correctly
         * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
         * have been completely destroyed during this process (it is likely that it would only be
         * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
         * method in {@link #onResume()} to guarantee that it will be called.
         */
        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();
                }
            }
        }
    
    /**
         * This is where we can add markers or lines, add listeners or move the camera. In this case, we
         * just add a marker near Africa.
         * <p/>
         * This should only be called once and when we are sure that {@link #mMap} is not null.
         */
        private void setUpMap() {
            //mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
            mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    
            mMap.setMyLocationEnabled(true);
            //Move the map to a specific point
    
    
        }