我想在 fragment 中显示谷歌地图。世界地图已显示,但标记将被忽略。 希望有些人可以帮助我解决我的问题。 请在下面找到我的代码:
MapsFragment.java:
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.GoogleMap;
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 MapsFragment extends SupportMapFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
View root = inflater.inflate(R.layout.fragment_map, null, false);
initilizeMap();
return root;
}
private void initilizeMap()
{
SupportMapFragment mSupportMapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
if (mSupportMapFragment == null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
mSupportMapFragment = SupportMapFragment.newInstance();
fragmentTransaction.replace(R.id.map, mSupportMapFragment).commit();
}
if (mSupportMapFragment != null)
{
GoogleMap googleMap = mSupportMapFragment.getMap();
if (googleMap != null)
googleMap.addMarker(new MarkerOptions().position(new LatLng(10.1253,10.5868)));
}
}
}
fragment_map.xml(布局):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1.03"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="@+id/map" />
</LinearLayout>
设置APIKey和权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
谢谢!
最佳答案
不要使用 getMap()
方法,它已被弃用。您应该使用 getMapAsync()
。查看this link .您的 mapsFragments 需要实现 OnMapReadyCallback界面。
关于带有 fragment 内标记的Android谷歌地图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34976508/