繁体   English   中英

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

[英]Unable to show current location on google map?

我正在开发在google map上显示我当前位置的应用程序。我已经尽力了,但无法在google map上显示我的当前位置。 下面是我的代码。 '

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开启状态,但仍未显示当前位置

我在设备上试用了您的代码,然后四处走动就能看到当前位置( 我认为代码触发了onLocationChanged )。 它显示了蓝色的当前位置标记,可以验证您的Google Maps代码是否正确触发( 如果正确触发)。

关于您发布的代码,注意到您正在调用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来查看location的值是什么(原来是null首先使用模拟器对其进行了测试 ))。 我认为这会使地图不显示当前位置标记。 我在清单中添加的唯一权限是ACCESS_COARSE_LOCATIONACCESS_FINE_LOCATIONWRITE_EXTERNAL_STORAGE

PS:我删除return; 在您的if statement ,出现与权限相关的错误。 我所做的就是从这个答案中以最快的方式进行操作( 我刚刚将targetSdkVersion修改为22 )。

决定从现在开始在设备中对其进行测试。 最初,地图能够加载,但未显示任何当前位置标记,只是显示了地图右上角的“ 定位我”按钮,我还添加了一个Toast以显示location的值,仍然显示为null 然后我走了一段时间,那是当地图摄影机对准并放大到我的当前位置时

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

所以我觉得你这里的主要问题不是 不能够在地图上显示当前位置 ,但无法通过正确的数据,其中的地图应该直接 我环顾了片刻,看到了一些与您的代码非常相似的示例,其中仅包含一些示例。 答案中提到的示例项目是有关如何使用Location一个很好的示例( 答案本身很有用 )。

希望这可以帮助。 祝好运。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM