地图不会显示带标记的当前位置

时间:2017-11-20 16:40:22

标签: android google-maps

我正在使用导航抽屉,在我需要提供谷歌地图的一个选项中。我想显示用户的当前位置,并在其位置用标记连续更新。 Foll是我的代码

public class MapView extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener{

    GoogleMap m_map;
    boolean mapReady = false;
    private GoogleApiClient googleApiClient;
    private LocationListener locationListener;
    private Marker marker;

    public MapView() {
        // Required empty public constructor
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_map_view, container, false);
        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);

        mapFragment.getMapAsync(this);


        return view;
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mapReady = true;
        m_map = googleMap;

        googleApiClient = new GoogleApiClient.Builder(getActivity()).addApi(LocationServices.API).addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
        googleApiClient.connect();


    }






    @Override
    public void onConnected(@Nullable Bundle bundle) {
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                gotoLocation(location.getLatitude(), location.getLongitude(), 15);
            }
        };
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(5000);
        locationRequest.setFastestInterval(1000);
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, locationListener);
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED &&
                    grantResults[1] == PackageManager.PERMISSION_GRANTED && grantResults[2] == PackageManager.PERMISSION_GRANTED) {
                showLocation();
            }
        }
    }

    public void showLocation() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (getActivity().checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && getActivity().checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED

                    ) {
                requestPermissions(new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,
                        android.Manifest.permission.ACCESS_FINE_LOCATION,
                }, 0);
            } else {
                Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
                if (location == null) {
                    Toast.makeText(getActivity(), "Failed", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getActivity(), "Failed", Toast.LENGTH_LONG).show();
                    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 15);
                    m_map.animateCamera(cameraUpdate);
                }
            }

        } else {
            Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
            if (location == null) {
                Toast.makeText(getActivity(), "Failed", Toast.LENGTH_LONG).show();
            } else {
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 15);
                m_map.animateCamera(cameraUpdate);
            }

        }


    }

    public void gotoLocation(double lat, double lng, float zoom) {
        LatLng latLng = new LatLng(lat, lng);
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, zoom);
        m_map.moveCamera(cameraUpdate);
        if(marker!=null){
            marker.remove();
        }


        MarkerOptions markerOptions=new MarkerOptions()
                .position(new LatLng(lat,lng))
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.bg));
        //dont put image in mipmap for marker
        marker= m_map.addMarker(markerOptions);



    }

    @Override
    public void onPause() {
        super.onPause();
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, locationListener);
    }

}

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="sawant.pritish.com.sharingfoodandhappiness.MapView.MapView">

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />



</FrameLayout>

我添加了必要的权限,如互联网,访问精细和粗略的位置和访问网络状态。我添加了元数据标签并使用了功能标签。有人可以帮忙。

1 个答案:

答案 0 :(得分:0)

您可以通过更简单的解决方案实现这一目标:只需致电

即可

onMapReady(GoogleMap googleMap)

android.Manifest.permission.ACCESS_COARSE_LOCATIONandroid.Manifest.permission.ACCESS_FINE_LOCATION权限授予后的public class MainActivity extends AppCompatActivity implements OnMapReadyCallback { private static final int LOCATION_PERMISSION_REQUEST_CODE = 101; private GoogleMap mGoogleMap; private MapFragment mMapFragment; private void makeLocationPermissionRequest() { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMapFragment = (MapFragment) getFragmentManager() .findFragmentById(R.id.map_fragment); mMapFragment.getMapAsync(this); } private void showCurrentPositionMarker() { mGoogleMap.setMyLocationEnabled(true); } @Override public void onMapReady(GoogleMap googleMap) { mGoogleMap = googleMap; if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION); if (locationPermission != PackageManager.PERMISSION_GRANTED) { makeLocationPermissionRequest(); } else { showCurrentPositionMarker(); } } else { showCurrentPositionMarker(); } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case LOCATION_PERMISSION_REQUEST_CODE: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { showCurrentPositionMarker(); } else { } return; } } } } 回调中

。这样的事情:

{{1}}
相关问题