无法在谷歌地图上显示当前位置?

时间:2016-03-28 18:46:10

标签: java android google-maps gps

我正在开发应用程序,显示我在谷歌地图上的当前位置。我努力但我无法在谷歌地图上显示我当前的位置。 以下是我的代码。 “

public class HomeFragment extends Fragment implements OnMapReadyCallback, LocationListener {

    GoogleMap mMap;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    public void initGamp(View root) {

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

        // check if map is created successfully or not


    }

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

        initGamp(rootView);

        // Inflate the layout for this fragment
        return rootView;
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

        mMap = googleMap;

        // Add a marker in Sydney, Australia, and move the camera.
//        LatLng sydney = new LatLng(-34, 151);
//        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
//        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#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 ActivityCompat#requestPermissions for more details.
            return;
        }
        Log.i("MAP","BEFORE LOCATION");
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
        Log.i("MAP", "AFTER LOCATION");
        LocationManager locationManager = (LocationManager) getActivity().getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(bestProvider);
        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);

        Log.i("MAP", "END LOCATION");



    }

    @Override
    public void onLocationChanged(Location location) {

        Log.i("MAP","CHANGE LOCATION");

        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        LatLng latLng = new LatLng(latitude, longitude);
        mMap.addMarker(new MarkerOptions().position(latLng));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15));


    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {


    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

清单中的权限

<!-- Required to show current location -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

我已检查应用的GPS已开启,但仍未显示当前位置

1 个答案:

答案 0 :(得分:0)

我在设备上试用了你的代码,我能够看到当前位置 AFTER 一点点移动(我认为代码已触发onLocationChanged )。它显示了蓝色当前位置标记,用于验证Maps的代码是否正常 IF 正常触发。

关于您发布的代码,注意到您在此return;后呼叫if statement

if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

- 这使得它下面的代码无法访问。我认为这是一个因素,为什么当前位置由于某种原因没有出现。修改后(删除return; ),我可以继续下面的代码:

Log.i(""MAP"",""BEFORE LOCATION"");
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
        Log.i(""MAP"", ""AFTER LOCATION"");
        LocationManager locationManager = (LocationManager) getActivity().getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(bestProvider);
        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);

        Log.i(""MAP"", ""END LOCATION"");

- 在这里,我刚刚添加了Log来查看位置的值是什么,结果是 null 首先使用模拟器)。我认为这会导致地图不显示当前位置标记。我在清单中添加的唯一权限是ACCESS_COARSE_LOCATIONACCESS_FINE_LOCATIONWRITE_EXTERNAL_STORAGE

  

PS:我删除return;中的if statement后,出现了与权限相关的错误。我所做的是按照answer我刚刚将我的targetSdkVersion修改为22 )的最快方式。

决定从这里开始在设备中测试它。首先,地图能够加载,但没有显示任何当前位置标记,它只是显示地图右上角的 找到我 按钮,我也添加了Toast以显示位置的值,该值仍显示为null。然后我去了四处走动,那时 地图相机指向并放大到我当前的位置

  

在模拟器和设备上进行测试期间,已打开“位置”。 :)

所以我认为你在这里主要关注的是 无法在地图上显示当前位置但是无法传递正确的数据直接。我环顾了一会儿,看到了一些与你的代码非常相似的例子,它们只包含了一些。此answer中提到的示例项目是关于如何使用Location的一个很好的示例(答案本身很有用)。

希望这会有所帮助。祝你好运。