英文:
Integrate Map in Fragment instead of Activity
问题
public class MapFragment extends Fragment implements OnMapReadyCallback {
Location currentLocation;
FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_map, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(requireActivity());
fetchLastLocation();
}
private void fetchLastLocation() {
if (ActivityCompat.checkSelfPermission(requireActivity(),
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(requireActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(requireActivity(), new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
return;
}
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(requireActivity(), new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
currentLocation = location;
Toast.makeText(requireContext(), currentLocation.getLatitude()
+ "" + currentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
SupportMapFragment supportMapFragment = (SupportMapFragment)
requireActivity().getSupportFragmentManager().findFragmentById(R.id.google_map);
supportMapFragment.getMapAsync(MapFragment.this);
}
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("I am here.");
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13));
googleMap.addMarker(markerOptions);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
fetchLastLocation();
}
break;
}
}
}
英文:
I want to add Google Map in a fragment which is inside Main Activity.
But I get an error in the below statements.
-
this
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
-
getApplicationContext()
Toast.makeText(getApplicationContext(), currentLocation.getLatitude()
-
getSupportFragmentManager()
getSupportFragmentManager().findFragmentById(R.id.google_map);
The same code works in an Activity. As this is coded in a Fragment, what are the changes that should be done?
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
public class MapFragment extends Fragment implements OnMapReadyCallback {
Location currentLocation;
FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_map, container, false);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
fetchLastLocation();
}
private void fetchLastLocation() {
if (ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
return;
}
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if(location != null){
currentLocation = location;
Toast.makeText(getApplicationContext(), currentLocation.getLatitude()
+""+currentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.google_map);
supportMapFragment.getMapAsync(MapFragment.this);
}
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("I am here.");
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13));
googleMap.addMarker(markerOptions);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case REQUEST_CODE:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
fetchLastLocation();
}
break;
}
}
}
</details>
# 答案1
**得分**: 0
尝试在这里使用 `getActivity()` 替代 `this`
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
并且在这里使用 `getActivity()` 替代 `getApplicationContext()`
第三个问题 `getActivity().getSupportFragmentManager()`
更新
尝试
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient((Context)getActivity());
<details>
<summary>英文:</summary>
Try using `getActivity()` instead of `this` here
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
and use `getActivity()` instead of `getApplicationContext()`
third problem `getActivity().getSupportFragmentManager()`
Update
Try
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient((Context)getActivity());
</details>
# 答案2
**得分**: 0
我找到了这个答案。无论谁在这方面遇到麻烦都可以使用下面的方法:
而不是:
```java
return inflater.inflate(R.layout.fragment_map, container, false);
我编写的代码如下:
View v = inflater.inflate(R.layout.fragment_map, container, false);
return v;
然后:
- 替换使用
this
为getActivity()
- 替换使用
getApplicationContext()
为v.getApplicationContext()
- 替换使用
getSupportFragmentManager()
为v.getSupportFragmentManager()
英文:
I found this answer. Whoever finds trouble in this can use the below way:
Instead of
return inflater.inflate(R.layout.fragment_map, container, false);
I coded as,
View v = inflater.inflate(R.layout.fragment_map, container, false);
return v;
and then
- Instead of using
this
usegetActivity()
- Instead of
getApplicationContext()
usev.getApplicationContext()
- Instead of
getSupportFragmentManager()
usev.getSupportFragmentManager()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论