Show my current location in the Google Map

前端 未结 5 492
-上瘾入骨i
-上瘾入骨i 2021-01-16 01:19

Finally I succeed to display the map,Now,I want to show my current location, I tried by using these code but it didn\'t work when I clicked the my location button in the to

5条回答
  •  野的像风
    2021-01-16 01:50

    Use following code:

    //Zoom to the current location
    public Location getMyLocation() {
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
    
        Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
        if (location != null) {
            map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(location.getLatitude(), location.getLongitude()), 13));
    
            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
                    .zoom(17)                   // Sets the zoom
                    .bearing(90)                // Sets the orientation of the camera to east
                    .tilt(40)                   // Sets the tilt of the camera to 30 degrees
                    .build();                   // Creates a CameraPosition from the builder
            map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    
        }
    
        return location;
    }
    

    Then call this method insode your onCreate

    Hope this helps :)

提交回复
热议问题