获取Google地图上的当前位置无法正常工作?

时间:2015-10-31 01:09:12

标签: android google-maps dictionary google-maps-api-3

我把我当前的位置放在地图上的标记它工作正常但有时候它不能正常工作我不知道为什么帮助我在这段代码中找出我的错。这是我获取当前位置的代码,并将标记放在地图上。

这是我的java文件MapActivity.java

try {
        if (googleMap == null) {
            googleMap = ((MapFragment) getActivity().getFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
            googleMap.getUiSettings().setZoomControlsEnabled(false);
        }
        GoogleMapOptions options = new GoogleMapOptions();
        options.mapType(GoogleMap.MAP_TYPE_NORMAL).compassEnabled(false)
                .rotateGesturesEnabled(false).tiltGesturesEnabled(false);

        // this is for get current location
        LocationManager locationManager = (LocationManager) getActivity()
                .getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        Location location = locationManager
                .getLastKnownLocation(locationManager.getBestProvider(
                        criteria, true));

        if (location != null) {
            currentLatLng = (new LatLng(location.getLatitude(),
                    location.getLongitude()));

            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(location.getLatitude(), location
                            .getLongitude()), 13));

            Marker marker = googleMap.addMarker(new MarkerOptions()
                    .position(currentLatLng));

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(currentLatLng).zoom(12)
                    .bearing(90).tilt(40).build();

            googleMap.animateCamera(CameraUpdateFactory
                    .newCameraPosition(cameraPosition));

            CircleOptions circleOptions = new CircleOptions()
                    .center(currentLatLng).radius(200)
                    .fillColor(Color.TRANSPARENT)
                    .strokeColor(0x10000000).strokeWidth(5);

            mCircle = googleMap.addCircle(circleOptions);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

2 个答案:

答案 0 :(得分:1)

调用animateCamera()后,您需要调用 setMyLocationEnabled(true),例如

    googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(location.getLatitude(), location
                            .getLongitude()), 13));
    googleMap.setMyLocationEnabled(true);

答案 1 :(得分:0)

您是否尝试过以下代码?

googleMap.setMyLocationEnabled(true);