无法在android中显示地图标记

时间:2017-09-28 05:55:53

标签: android google-maps

我想在地图中添加地图标记。我有一个片段,我想在其中显示地图标记。我添加了com.google.android.gms:play-services-maps:10.0.1'在我的应用程序的gradle中。但我有一个错误,即

android.view.InflateException:二进制XML文件行#7:二进制XML文件行#7:错误膨胀类片段

// 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:orientation="vertical">

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

  </LinearLayout>

//地图代码

public class KantorenOfficeDetailsFragment extends Fragment implements View.OnClickListener, OnMapReadyCallback {

      GoogleMap googleMap;


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

       private void setUpMapIfNeeded() {
        if (googleMap == null) {
             SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
             mapFragment.getMapAsync(this);
             if (googleMap != null) {
                 setUpMap();
             }
        }
    }

   private void setUpMap() {
                googleMap.addMarker(new MarkerOptions().position(new LatLng(22.7253, 75.8655)).title("Indore"));    // here is marker Adding code
          }

    }

2 个答案:

答案 0 :(得分:0)

您没有初始化googleMap对象。

MapFragment Initialize必须像这样

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            mapFragment= (MyMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
        else
            mapFragment= (MyMapFragment) getFragmentManager().findFragmentById(R.id.map);

mapFragment.getMapAsync(this);

然后导入回调方法

@Override
public void onMapReady(GoogleMap map) {
    googleMap = map;
}

在内部回调方法

中调用此setUpMap
 if (googleMap != null) {
       setUpMap();
   }

您的OnMapReady必须像

@Override
    public void onMapReady(GoogleMap map) {
        googleMap = map;
       if (googleMap != null) {
           setUpMap();
       }
    }

希望它能帮到你

答案 1 :(得分:-2)

将您的xml更改为:

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<fragment
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="176dp" //whatever height you want
    android:name="com.google.android.gms.maps.SupportMapFragment" />

  </LinearLayout>

看到你的xml你的地图高度似乎是崩溃的唯一原因!!