集成地图至 Fragment 而非 Activity 中。

huangapple go评论67阅读模式
英文:

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.

  1. this fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

  2. getApplicationContext()
    Toast.makeText(getApplicationContext(), currentLocation.getLatitude()

  3. 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 &amp;&amp;
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&lt;Location&gt; task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener&lt;Location&gt;() {
@Override
public void onSuccess(Location location) {
if(location != null){
currentLocation = location;
Toast.makeText(getApplicationContext(), currentLocation.getLatitude()
+&quot;&quot;+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(&quot;I am here.&quot;);
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&gt;0 &amp;&amp; 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;

然后:

  1. 替换使用 thisgetActivity()
  2. 替换使用 getApplicationContext()v.getApplicationContext()
  3. 替换使用 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

  1. Instead of using this use getActivity()
  2. Instead of getApplicationContext() use v.getApplicationContext()
  3. Instead of getSupportFragmentManager() use v.getSupportFragmentManager()

huangapple
  • 本文由 发表于 2020年9月24日 21:12:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/64047221.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定