Android studio-无法在Fragment活动(抽屉菜单)中实现Google地图)>

问题描述 投票:0回答:1

I am trying to make this code working within fragment in menu drawer but seems to be imposible. Can someone help me?

公共类HomeFragment扩展Fragment实现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();
    }
}

} [在此处输入图片描述] [2]

错误:找不到符号方法getSupportFragmentManager()错误:找不到符号方法findViewById(int)错误:找不到符号方法findViewById(int)错误:类型不兼容:HomeFragment无法转换为上下文错误:找不到符号方法getSystemService(String)错误:找不到符号方法getApplicationContext()错误:找不到符号方法checkSelfPermission(String)错误:找不到符号方法checkSelfPermission(String)错误:类型不兼容:HomeFragment无法转换为上下文错误:类型不兼容:HomeFragment无法转换为Activity错误:找不到符号方法getApplicationContext()

我正在尝试使此代码在菜单抽屉中的片段内工作,但似乎是不可能的。有人能帮我吗?公共类HomeFragment扩展Fragment实现OnMapReadyCallback {...

android menu maps fragment drawer
1个回答
0
投票

您必须修改onCreateView方法

© www.soinside.com 2019 - 2024. All rights reserved.