我在Android上使用GoogleMaps API时遇到问题,我有一个需要里面的mapsFragment的片段,我可以将地图放在视图中,并在布局上使用此代码
<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上添加标记或更改任何内容时出现问题,因为我需要使用此代码获取地图
GoogleMaps googleMap = SupportMapFragment.newInstance(new GoogleMapOptions().zOrderOnTop(true)).getMap();
执行此类addMarker
,moveCamera
,animateCamera
之类的操作,但SupportMapFragment.newInstance始终返回null。所有这些代码都在onActivityCreated中执行,因为如果我尝试在onCreateView上处理这段代码,那么我不知道我可以在片段中做什么来获取GoogleMaps的地图
请帮助我!!
答案 0 :(得分: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);
}
}