2016-01-28 50 views
0

我有一個問題白衣Android上的Google Maps API,我有誰需要內部mapsFragment一個片段,我可以把地圖的視圖中使用此代碼的佈局的Android的GetMap()返回我空

<RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:id="@+id/map_container"> 
</RelativeLayout> 

以及與此代碼,我可以爲mapsFragment

SupportMapFragment fragment = SupportMapFragment.newInstance(); 
GoogleMaps googleMap = SupportMapFragment.newInstance(new GoogleMapOptions().zOrderOnTop(true)).getMap(); 
FragmentTransaction ft = getFragmentManager().beginTransaction(); 
ft.replace(R.id.map_container, fragment); 
ft.commit(); 

問題是當我試圖把一個標記或在mapFragment改變任何東西,因爲我需要這個代碼

獲取地圖變化

做這樣的東西addMarkermoveCameraanimateCamera但SupportMapFragment.newInstance總是返回我空。所有這些代碼都在onActivityCreated中執行,因爲如果我嘗試在onCreateView上處理此代碼,所以我不知道我可以在片段中做什麼來獲取GoogleMaps的地圖

請幫助我!

+0

仔細閱讀谷歌地圖API文檔,以確定正確的生命週期。 –

+0

您正在創建兩個SupportMapFragment實例,並且您沒有在您用於FragmentTransaction的SupportMapFragment實例上調用'getMap()'。 –

回答

2

您撥打電話時地圖尚未準備好。更換getMap()with getMapAsync(),然後在OnMapReadyCallback及其onMapReady()方法進行地圖的其餘配置:

/*** 
Copyright (c) 2012 CommonsWare, LLC 
Licensed under the Apache License, Version 2.0 (the "License"); you may not 
use this file except in compliance with the License. You may obtain a copy 
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required 
by applicable law or agreed to in writing, software distributed under the 
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 
OF ANY KIND, either express or implied. See the License for the specific 
language governing permissions and limitations under the License. 

From _The Busy Coder's Guide to Android Development_ 
https://commonsware.com/Android 
*/ 

package com.commonsware.android.mapsv2.nooyawk; 

import android.os.Bundle; 
import com.google.android.gms.maps.CameraUpdate; 
import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.MapFragment; 
import com.google.android.gms.maps.OnMapReadyCallback; 
import com.google.android.gms.maps.model.LatLng; 

public class MainActivity extends AbstractMapActivity implements 
    OnMapReadyCallback { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    if (readyToGo()) { 
     setContentView(R.layout.activity_main); 

     MapFragment mapFrag= 
      (MapFragment)getFragmentManager().findFragmentById(R.id.map); 

     if (savedInstanceState == null) { 
     mapFrag.getMapAsync(this); 
     } 
    } 
    } 

    @Override 
    public void onMapReady(GoogleMap map) { 
    CameraUpdate center= 
     CameraUpdateFactory.newLatLng(new LatLng(40.76793169992044, 
      -73.98180484771729)); 
    CameraUpdate zoom=CameraUpdateFactory.zoomTo(15); 

    map.moveCamera(center); 
    map.animateCamera(zoom); 
    } 
} 

(從this sample appthis book

+0

這個工作很好,謝謝 –

相關問題