Невозможно внедрить карты Google в операции Fragment (Меню Drawer) - PullRequest
0 голосов
/ 03 ноября 2019

Я пытаюсь заставить этот код работать в fragment в ящике меню, но кажется невозможным. Кто-нибудь может мне помочь?

public class HomeFragment extends Fragment implements OnMapReadyCallback {

    private HomeViewModel homeViewModel;

    private GoogleMap mMap;
    LocationManager locationManager;
    LocationListener locationListener;
    DrawerLayout drawer;
    ProgressDialog dialog;
    double[][] cords;
    LatLonCoordinate[] arrayCords;
    JSONArray arr;
    ImageView recentreLoc;
    ImageView getInfo;
    ImageView burger;
    ImageView car;
    FragmentActivity fragAct;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        //homeViewModel =
          //
        //      ViewModelProviders.of(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.

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

        recentreLoc = (ImageView) findViewById(R.id.icon_me);
        getInfo = (ImageView) findViewById(R.id.icon_info);

        return root;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
            }
        }
    }

    public void openDrawer(View view){
        drawer.openDrawer(Gravity.LEFT);
        //drawer.openDrawer(1,true);
    }
    public void recentreLocation(View view){
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
        //setting last known location
        Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        //
        LatLng me = new LatLng(lastKnownLocation.getLatitude(),lastKnownLocation.getLongitude());
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(me, 16f));
    }
    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(final GoogleMap googleMap) {
        mMap = googleMap;
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                //Toast.makeText(MapsActivity.this,location.toString(),Toast.LENGTH_LONG).show();
                //mMap.clear();
                LatLng me = new LatLng(location.getLatitude(), location.getLongitude());
                mMap.addMarker(new MarkerOptions().position(me).title("Your location"));
                //mMap.moveCamera(CameraUpdateFactory.newLatLng(me));
                Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
                try {
                    //getting info about location
                    List<Address> listaddresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);    //1 - show the best match (result)
                    if (listaddresses != null && listaddresses.size() > 0) {
                        //Log.i("Place", listaddresses.get(0).toString());
                        //Deriving useful info
                        String a = "";
                        if (listaddresses.get(0).getAdminArea() != null) {
                            a += listaddresses.get(0).getAdminArea() + " ";
                        }
                        if (listaddresses.get(0).getLocality() != null) {
                            a += listaddresses.get(0).getLocality() + " ";
                        }
                        if (listaddresses.get(0).getThoroughfare() != null) {
                            a += listaddresses.get(0).getThoroughfare();
                        }
                        //Toast.makeText(getApplicationContext(), a, Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }
            @Override
            public void onProviderEnabled(String provider) {
            }
            @Override
            public void onProviderDisabled(String provider) {
            }
        };
        if (Build.VERSION.SDK_INT < 23) {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    Activity#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for Activity#requestPermissions for more details.
                return;
            }
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
        } else {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            } else {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
                //setting last known location
                Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                //
                mMap.clear();
                if(lastKnownLocation!= null) {
                    LatLng me = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
                    //BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.defaultphoto);
                    int height = 100;
                    int width = 100;
                    BitmapDrawable bitmapdraw=(BitmapDrawable)getResources().getDrawable(R.drawable.defaultphoto);
                    Bitmap b=bitmapdraw.getBitmap();
                    Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
                    mMap.addMarker(new MarkerOptions().position(me).icon(BitmapDescriptorFactory.fromBitmap(smallMarker)).title("Your location"));
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(me, 16f));
                }
            }
        }
        InputStream inputStream = getApplicationContext().getResources().openRawResource(R.raw.hdb_carpark_information);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
        String line = "";
        ArrayList<String> arrayList;
        //double [] cords ;
        cords = new double[2113][2];
        arrayCords = new LatLonCoordinate[2113];
        int i=0;
        try {
            //dialog.show();
            //dialog = ProgressDialog.show(MapsActivity.this, "",
            //      "Connecting. Please wait...", true);
            reader.readLine();
            while ((line = reader.readLine()) != null) {
                arrayList = new ArrayList<>();
                //Log.i("line", line);
                String[] splitted = line.split("\",\"");
                Log.i("cords",splitted[2]+" "+splitted[3]);
                cords[i][0] = Double.parseDouble(splitted[2]);
                cords[i][1] = Double.parseDouble(splitted[3]);
                SVY21Coordinate svy21Coordinate = new SVY21Coordinate(cords[i][1],cords[i][0]);
                arrayCords[i] = SVY21.computeLatLon(svy21Coordinate);
                mMap.addMarker(new MarkerOptions().position(new LatLng(arrayCords[i].getLatitude(),arrayCords[i].getLongitude()))
                        .title(splitted[1])
                        .snippet(splitted[4]+"\n"+splitted[5]+"\n"+splitted[6]+"\n"+splitted[7]+"\n"+splitted[8]));
                i++;
            }
            //dialog.dismiss();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
} 

Снимок экрана ошибки экрана

Ошибка:

cannot find symbol method getSupportFragmentManager()   
cannot find symbol method findViewById(int) 
error: cannot find symbol method findViewById(int)  
error: incompatible types: HomeFragment cannot be converted to Context  
error: cannot find symbol method getSystemService(String)   
error: cannot find symbol method getApplicationContext()    
error: cannot find symbol method checkSelfPermission(String)    
error: cannot find symbol method checkSelfPermission(String)    
error: incompatible types: HomeFragment cannot be converted to Context  
error: incompatible types: HomeFragment cannot be converted to Activity 
error: cannot find symbol method getApplicationContext()

1 Ответ

0 голосов
/ 03 ноября 2019

Вы должны изменить свой метод onCreateView

public class HomeFragment extends Fragment {

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.location_fragment, container, false);

        mMapView = (MapView) rootView.findViewById(R.id.mapView);
        mMapView.onCreate(savedInstanceState);

        mMapView.onResume(); // needed to get the map to display immediately

        try {
            MapsInitializer.initialize(getActivity().getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }

        mMapView.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap mMap) {
                googleMap = mMap;

                // For showing a move to my location button
                googleMap.setMyLocationEnabled(true);

                // For dropping a marker at a point on the Map
                LatLng sydney = new LatLng(-34, 151);
                googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));

                // For zooming automatically to the location of the marker
                CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
                googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            }
        });

        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }
}
...