【问题标题】:Add SupportMapFragment to a LinearLayout将 SupportMapFragment 添加到 LinearLayout
【发布时间】:2016-03-18 22:17:39
【问题描述】:

我需要添加一个使用 AndroidStudio 创建的 SupportMapFragment。使用它的片段活动工作正常。它在悉尼显示带有标记的地图。 但我需要将该地图放在一个 Layout(即 LinearLayout)上以添加按钮并与地图进行交互。

我创建了一个类 MapsActivity.java 及其对应的布局 activity_maps.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Some Text"
        android:id="@+id/textView" />


    <fragment xmlns:map="http://schemas.android.com/apk/res-auto"
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:scrollbars="vertical"
        class="com.google.android.gms.maps.SupportMapFragment"/>

</LinearLayout>

既然如此:public class MapsActivity extends AppCompatActivity,在 MainActivity.onCreate() 里面我试过了:

1)

    android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
    SupportMapFragment mapFragment = SupportMapFragment.newInstance();
    manager.beginTransaction().replace(R.id.map, mapFragment).commit();
    setContentView(R.layout.activity_maps);
    GoogleMap mMap = mapFragment.getMap();
    // NOT GOOD: nMap is null.

2)

    FragmentManager manager = getChildFragmentManager();
    [...]
    // NOT GOOD: Cannot resolve method getChildFragmentManager.

3)

    GoogleMap mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    // NOT GOOD: nMap is null.

接下来我可以尝试什么?

【问题讨论】:

标签: android google-maps android-layout


【解决方案1】:

试试这样。修改第一个

您正在创建新的MapFragment 使用 SupportMapFragment.newInstance(); 而不是从 xml 获取 地图片段

FragmentManager myFragmentManager = getSupportFragmentManager();
    mapFragment = (SupportMapFragment) myFragmentManager
            .findFragmentById(R.id.map);

    map = mapFragment.getMap();

【讨论】:

  • 对,我改正了,还是不行:mapFragment 还是 Null at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap com.google.android.gms.maps.SupportMapFragment.getMap()' on a null object reference
  • 发现另一个错误。方法在setContentView(R.layout.activity_maps);之前被调用 谢谢你的帮助!
【解决方案2】:

让您的Activity 实现OnMapReadyCallback。例如

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

onCreate,在setContentView 之后,你做

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

onMapReady 被调用时,你可以使用googleMap

@Override
public void onMapReady(GoogleMap googleMap) {

GoogleMap 对象准备好供您使用可能需要一段时间,因此 getMapAsyncOnMapReadyCallback

【讨论】:

    【解决方案3】:

    我在这里发布了谁会感兴趣的完整答案,我发现它不是那么直观。这使您可以将地图添加到自定义布局中。

    public class MapsActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_maps);
    
            FragmentManager myFragmentManager = getSupportFragmentManager();
            SupportMapFragment mapFragment = (SupportMapFragment) myFragmentManager.findFragmentById(R.id.map);
            GoogleMap mMap = mapFragment.getMap();
    
            // Add a marker in Sydney and move the camera
            LatLng sydney = new LatLng(-35, 152);
            mMap.addMarker(new MarkerOptions().position(sydney).title("Marker near Sidney"));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        }
    
    }
    

    布局:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Some Text"
            android:id="@+id/textView" />
    
    
        <fragment xmlns:map="http://schemas.android.com/apk/res-auto"
            android:id="@+id/map"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:scrollbars="vertical"
            class="com.google.android.gms.maps.SupportMapFragment"/>
    
    </LinearLayout>
    

    【讨论】:

    • 您能发布一个更新的解决方案吗? ,getMap() 已被弃用。谢谢!
    【解决方案4】:

    这种方式可以在屏幕上显示谷歌地图

    <fragment
        android:id="@+id/map"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    
    public class RouteFinderActivity extends AppCompatActivity implements OnMapReadyCallback {
    
        GoogleMap map;
        Location location;
        Button btn_search_route;
        EditText et_source, et_destination;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_route_finder);
            btn_search_route = findViewById(R.id.btn_search_route);
            et_source = findViewById(R.id.et_source);
            et_destination = findViewById(R.id.et_destination);
    
            btn_search_route.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String source = et_source.getText().toString();
                    String destination = et_destination.getText().toString();
    
                    if (TextUtils.isEmpty(source)) {
                        et_source.setError("Enter Soruce point");
                    } else if (TextUtils.isEmpty(destination)) {
                        et_destination.setError("Enter Destination Point");
                    } else {
                        String sendstring="http://maps.google.com/maps?saddr=" +
                                source +
                                "&daddr=" +
                                destination;
                        Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                                Uri.parse(sendstring));
                        startActivity(intent);
                    }
                }
    
            });
    
            ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMapAsync(this);
        }
    
        @Override
        public void onMapReady(GoogleMap googleMap) {
            map = googleMap;
            map.setMapType(1);
            map.setMyLocationEnabled(true);
    
            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            Criteria criteria = new Criteria();
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
    
                location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
    
                if (location != null) {
                    //zoom
                    CameraPosition cameraPosition = new CameraPosition.Builder()
                            .zoom(17)
                            .target(new LatLng(location.getLatitude(), location.getLongitude()))
                            .bearing(90)
                            .tilt(40)
                            .build();
                    map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                }
            }
        }
    }
    

    清单

    <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="apikeymap" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      相关资源
      最近更新 更多