带有locationButton的地图片段

时间:2019-05-24 16:02:44

标签: android google-maps android-fragments android-fragmentactivity onsaveinstancestate

我一直在为大学做一个应用程序,它将通过画线(而不是在道路上)显示对象的行为方式,而我仅通过一项活动就做了一个。 我接下来要做的是尝试做同样的事情,但片段化 而且我一直在掠夺战利品,但我仍然真的不知道并不确定如何实现LocalizationButton和onSaveInstanceState以及我选择地图模式的菜单选项。

所以我制作了secound应用程序,其中实现了2个片段,现在我必须实现类似的方法: enableMyLocation onRequestPermissionsResult onSaveInstanceState

还有设置地图模式,我选择地图模式的菜单选项之类的东西

问题是我应该在哪里实施,我应该注意什么或更改?

我所做的代码(现在我必须作为片段来工作)

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {


    private static final int REQUEST_LOCATION_PERMISSION = 1;

    public static final float INITIAL_ZOOM = 10f;

    public float current_zoom = NULL;
    public LatLng current_target = new LatLng(NULL, NULL);
    public float current_bearing = NULL;
    public String current_map_mode = "day";

    private GoogleMap mMap;

    int size=10;

    ArrayList<LatLng> points_of_LatLng = new ArrayList<LatLng>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);


        SupportMapFragment mapFragment = SupportMapFragment.newInstance();
        getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, mapFragment).commit();
        mapFragment.getMapAsync(this);

        double a;
        double b;
        for(int x=0;x<size;x++){
            Random generator = new Random();
            a=(generator.nextDouble()*0.5)+53.425238;
            b=(generator.nextDouble()*0.5)+14.5355009;

            points_of_LatLng.add(new LatLng(a,b));
            Log.i("LatLng_values","Array : "+String.valueOf(points_of_LatLng.get(x)));
        }
        Log.i("LatLng_values","Array : "+String.valueOf(points_of_LatLng.size()));


        if (savedInstanceState != null) {
            points_of_LatLng.clear();
            points_of_LatLng = savedInstanceState.getParcelableArrayList("savedList");

            current_zoom = savedInstanceState.getFloat("savedZoom");
            current_target = savedInstanceState.getParcelable("savedTarget") ;
            current_bearing = savedInstanceState.getFloat("savedBearing");
            current_map_mode = savedInstanceState.getString("savedMapMode");
        }


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.map_options, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.normal_map:
                mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                try {
                    boolean success = mMap.setMapStyle(
                            MapStyleOptions.loadRawResourceStyle(this, R.raw.mapy_style_day));
                            current_map_mode = "day";

                    if (!success) {
                        Log.e("Set_map_style", "Style parsing failed.");
                    }
                } catch (Resources.NotFoundException e) {
                    Log.e("Set_map_style", "Can't find style. Error: ", e);
                }
                return true;
            case R.id.night_mode:
                mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                try {
                    boolean success = mMap.setMapStyle(
                            MapStyleOptions.loadRawResourceStyle(this, R.raw.map_style_night));
                            current_map_mode = "night";
                    if (!success) {
                        Log.e("Set_map_style", "Style parsing failed.");
                }
                } catch (Resources.NotFoundException e) {
                    Log.e("Set_map_style", "Can't find style. Error: ", e);
                }
                return true;
            case R.id.satellite_map:
                mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
                current_map_mode = "satellite";
                return true;
            case R.id.terrain_map:
                mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
                current_map_mode = "terrain";
                return true;
            case R.id.info:

                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

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


        LatLng myStartLocation = new LatLng(53.425238, 14.5355009);

        if(current_zoom==NULL ){
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myStartLocation, INITIAL_ZOOM));
        }
            else{
            mMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder()
                    .target(current_target)
                    .zoom(current_zoom)
                    .bearing(current_bearing)
                    .build()));
        }

        enableMyLocation(mMap);

        mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener(){
            @Override
            public boolean onMyLocationButtonClick()
            {

                if(isLocationEnabled(getApplicationContext())) {

                }
                else{
                    Toast toast = Toast.makeText(getApplicationContext(), "Włącz lokalizacje.", Toast.LENGTH_LONG);
                    toast.show();
                }
                return false;
            }
        });


        drawn_line(this.points_of_LatLng,this.mMap);


        if (current_zoom!=NULL) switch (current_map_mode) {
            case "day":

                mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                try {
                    boolean success = mMap.setMapStyle(
                            MapStyleOptions.loadRawResourceStyle(this, R.raw.mapy_style_day));

                    if (!success) {
                        Log.e("Set_map_style", "Style parsing failed.");
                    }
                } catch (Resources.NotFoundException e) {
                    Log.e("Set_map_style", "Can't find style. Error: ", e);
                }
                break;
            case "night":

                mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                try {
                    boolean success = mMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this, R.raw.map_style_night));
                    if (!success) {
                        Log.e("Set_map_style", "Style parsing failed.");
                    }
                } catch (Resources.NotFoundException e) {
                    Log.e("Set_map_style", "Can't find style. Error: ", e);
                }
                break;
            case "satellite":
                mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
                break;
            case "terrain":
                mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
                break;

            default:

                break;
        }

    }
    /**
     * Sprawdza czy jest pozwolenie na lokację
     */
    private void enableMyLocation(GoogleMap map) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { map.setMyLocationEnabled(true);
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {

        switch (requestCode) {
            case REQUEST_LOCATION_PERMISSION:
                if (grantResults.length > 0
                        && grantResults[0]
                        == PackageManager.PERMISSION_GRANTED) { enableMyLocation(mMap);
                    break;
                }
        }
    }

    public static boolean isLocationEnabled(Context context) {
        int locationMode = 0;
        String locationProviders;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            try {
                locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);

            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
                return false;
            }

            return locationMode != Settings.Secure.LOCATION_MODE_OFF;

        }else{
            locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        }


    }


    public void drawn_line(List<LatLng> tab , GoogleMap googleMap){
        for(int i=1;i<tab.size();i++){
            LatLng a = tab.get(i-1);
            LatLng b = tab.get(i);
            Polyline polyline = googleMap.addPolyline(new PolylineOptions()
                    .clickable(true)
                    .add(
                            a,
                            b
                    ));
            polyline.setColor(Color.RED);

            if(i==tab.size()-1){
                LatLng last_baloon_location = tab.get(i);
                mMap.addMarker(new MarkerOptions()
                        .position(last_baloon_location)
                        .title("Ostatnie znane polożenie")
                        .icon(BitmapDescriptorFactory.defaultMarker
                                (BitmapDescriptorFactory.HUE_ROSE)));
            }
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putParcelableArrayList("savedList", points_of_LatLng);
        outState.putFloat("savedZoom",mMap.getCameraPosition().zoom);
        outState.putParcelable("savedTarget",mMap.getCameraPosition().target);
        outState.putFloat("savedBearing",mMap.getCameraPosition().bearing);
        outState.putString("savedMapMode",current_map_mode);

        super.onSaveInstanceState(outState);
    }
}

应用我必须添加这些方法

我的片段代码map_fragment.xml

package com.example.android.madbaloon3;

public class MapFragment extends Fragment implements OnMapReadyCallback {

    private static final int REQUEST_LOCATION_PERMISSION = 1;

    public static final float INITIAL_ZOOM = 10f;

    public float current_zoom = NULL;
    public LatLng current_target = new LatLng(NULL, NULL);
    public float current_bearing = NULL;
    public String current_map_mode = "day";

    private GoogleMap mMap;

    int size=10;

    ArrayList<LatLng> points_of_LatLng = new ArrayList<LatLng>();


    public MapFragment() {
        // Required empty public constructor
    }

    SupportMapFragment mapFragment;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment

       View v = inflater.inflate(R.layout.fragment_map, container, false);

        mapFragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
        if(mapFragment==null){
            FragmentManager fm = getFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            mapFragment = SupportMapFragment.newInstance();
            ft.replace(R.id.map,mapFragment).commit();
        }
        mapFragment.getMapAsync(this);


       return v;
    }

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

        // Ustawia mapę w danym punkcie
        LatLng myStartLocation = new LatLng(53.425238, 14.5355009);

        if(current_zoom==NULL ){
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myStartLocation, INITIAL_ZOOM));
        }
        else{
            mMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder()
                    .target(current_target)
                    .zoom(current_zoom)
                    .bearing(current_bearing)
                    .build()));
        }

    }
}


conntent_main.xml的布局

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/app_bar_main">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:layout_editor_absoluteY="0dp">

        <fragment
            android:id="@+id/Mapfragment"
            android:name="com.example.android.madbaloon3.MapFragment"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="25"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:layout="@layout/fragment_map" />

        <fragment
            android:id="@+id/Datafragment"
            android:name="com.example.android.madbaloon3.DataFragment"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:layout="@layout/fragment_data" />

    </LinearLayout>



</android.support.constraint.ConstraintLayout>

map_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity" >
    <FrameLayout
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MapsActivity" />
</FrameLayout>

0 个答案:

没有答案