Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/213.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android中使用FusedlocationProviderClient Api的实时位置跟踪问题_Java_Android_Google Maps_Location_Fusedlocationproviderclient - Fatal编程技术网

Java Android中使用FusedlocationProviderClient Api的实时位置跟踪问题

Java Android中使用FusedlocationProviderClient Api的实时位置跟踪问题,java,android,google-maps,location,fusedlocationproviderclient,Java,Android,Google Maps,Location,Fusedlocationproviderclient,我在Android Studio中的谷歌地图活动片段上试用了下面给出的代码,我甚至在手机上编译并运行了它,但我的位置没有显示出来。请帮我找到代码中的错误 package com.example.ambulance; import ... public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback { private GoogleMap googleMap; private

我在Android Studio中的谷歌地图活动片段上试用了下面给出的代码,我甚至在手机上编译并运行了它,但我的位置没有显示出来。请帮我找到代码中的错误

    package com.example.ambulance;

    import ...

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

private GoogleMap googleMap;
private FusedLocationProviderClient fusedLocationProviderClient;
private int REQUEST_ACCESS = 5445;
private boolean firstTimeFlag = true;
private Marker currentLocationMarker;
private static Location currentLocation;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.google_map);
    supportMapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap)
{
    this.googleMap = googleMap;
}

@Override
protected void onResume()
{
    super.onResume();
    if(isGooglePlayServicesAvailable())
    {
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        startLocationUpdates();
    }
}

private boolean isGooglePlayServicesAvailable()
{
    GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();

    int status = googleApiAvailability.isGooglePlayServicesAvailable(this);

    if(ConnectionResult.SUCCESS == status)
        return true;
    else
    {
        if(googleApiAvailability.isUserResolvableError(status))
            Toast.makeText(this, "Please Install Google Play Services to Use this Application", Toast.LENGTH_LONG).show();
    }
    return false;
}

private void startLocationUpdates()
{
    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(300);
    locationRequest.setSmallestDisplacement(1);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
    {
        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
            ActivityCompat.requestPermissions(MapsActivity.this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_ACCESS);
        return;
    }
    fusedLocationProviderClient.requestLocationUpdates(locationRequest, mLocationCallback, Looper.myLooper());
}

//Here we are defining the mLocationCallback object, that is used in the previous function.

private final LocationCallback mLocationCallback = new LocationCallback(){

    @Override
    public void onLocationResult(LocationResult locationResult)
    {
        super.onLocationResult(locationResult);
        if(locationResult.getLastLocation() == null)
            return;

        currentLocation = locationResult.getLastLocation();

        if(firstTimeFlag && googleMap != null)
        {
            animateCamera(currentLocation);
            firstTimeFlag = true;
        }
        showMarker(currentLocation);
    }
};

private void animateCamera(@NonNull Location location)
{
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(getCameraPositionWithBearing(latLng)));
}

@NonNull
private CameraPosition getCameraPositionWithBearing(LatLng latLng) {

    return new CameraPosition.Builder().target(latLng).zoom(16).build();

}

private void showMarker(@NonNull Location currentLocation)
{
    LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());

    if(currentLocationMarker == null)
        currentLocationMarker = googleMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.defaultMarker()).position(latLng));
    else
        MarkerAnimation.animateMarkerToGB(currentLocationMarker, latLng, new LatLngInterpolator.Spherical());
}
}


    package com.example.ambulance;

    import ...

public interface LatLngInterpolator
{
LatLng interpolate(float fraction, LatLng a, LatLng b);

class Spherical implements  LatLngInterpolator
{
    /* From github.com/googlemaps/android-maps-utils */

    @Override
    public LatLng interpolate(float fraction, LatLng from, LatLng to)
    {
        //http://en.wikipedia.org/wiki/Slerp

        double fromLat = toRadians(from.latitude);
        double fromLng = toRadians(from.longitude);
        double toLat = toRadians(to.latitude);
        double toLng = toRadians(to.longitude);
        double cosFromLat = cos(fromLat);
        double cosToLat = cos(toLat);

        //Computes Spherical interpolation co-efficients.

        double angle = computeAngleBetween(fromLat, fromLng, toLat, toLng);
        double sinAngle = sin(angle);

        if (sinAngle < 1E-6)
            return from;

        double a = sin((1 - fraction) * angle) / sinAngle;
        double b = sin(fraction * angle) / sinAngle;

        //Converts from polar to vector and interpolate.

        double x = a * cosFromLat * cos(fromLat) + b * cosToLat * cos(toLng);
        double y = a * cosFromLat * sin(fromLng) + b * cosToLat * sin(toLng);
        double z = a * sin(fromLat) + b * sin(toLat);

        //Converts interpolated vectors back to polar.

        double lat = atan2(z, sqrt(x*x + y*y));
        double lng = atan2(y, x);
        return new LatLng(toDegrees(lat), toDegrees(lng));
    }

    private double computeAngleBetween(double fromLat, double fromLng, double toLat, double toLng)
    {
        //Haversine's Formula

        double dLat = fromLat - toLat;
        double dLng = fromLng - toLng;
        return 2 * asin(sqrt(pow(sin(dLat / 2), 2) + cos(fromLat) * cos(toLat * pow(sin(dLng / 2), 2))));
    }
}
}


    package com.example.ambulance;

    import ...

public class MarkerAnimation {
    public static void animateMarkerToGB(final Marker marker, final LatLng finalPosition, final LatLngInterpolator latLngInterpolator) {
    final LatLng startPosition = marker.getPosition();
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    final Interpolator interpolator = new AccelerateDecelerateInterpolator();
    final float durationInMs = 2000;

    handler.post(new Runnable() {
        long elapsed;
        float t;
        float v;

        @Override
        public void run() {
            //Calculator Progress Using Interpolator.
            elapsed = SystemClock.uptimeMillis() - start;
            t = elapsed / durationInMs;
            v = interpolator.getInterpolation(t);

            marker.setPosition(latLngInterpolator.interpolate(v, startPosition, finalPosition));

            //Repeat till progress is complete.

            if (t < 1) {
                //Post again 16ms later.
                handler.postDelayed(this, 16);
            }

        }
    });
}
}
package com.example.救护车;
导入。。。
公共类MapsActivity扩展了AppCompatActivity在MapReadyCallback上的实现{
私人谷歌地图谷歌地图;
私有FusedLocationProviderClient FusedLocationProviderClient;
私有int请求_访问=5445;
私有布尔值firstTimeFlag=true;
专用标记currentLocationMarker;
私有静态定位;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_映射);
SupportMapFragment SupportMapFragment=(SupportMapFragment)getSupportFragmentManager();
supportMapFragment.getMapAsync(此文件);
}
@凌驾
4月1日公开作废(谷歌地图谷歌地图)
{
this.googleMap=谷歌地图;
}
@凌驾
受保护的void onResume()
{
super.onResume();
如果(isGooglePlayServicesAvailable())
{
fusedLocationProviderClient=LocationServices.getFusedLocationProviderClient(此);
startLocationUpdates();
}
}
私有布尔值isGooglePlayServicesAvailable()
{
GoogleAppAvailability GoogleAppAvailability=GoogleAppAvailability.getInstance();
int status=GooglePayAvailability.isGooglePlayServicesAvailable(此);
if(ConnectionResult.SUCCESS==状态)
返回true;
其他的
{
if(GoogleAppAvailability.isUserResolvableError(状态))
Toast.makeText(此“请安装Google Play服务以使用此应用程序”,Toast.LENGTH_LONG.show();
}
返回false;
}
private void startLocationUpdates()
{
LocationRequest LocationRequest=LocationRequest.create();
locationRequest.setPriority(locationRequest.PRIORITY\u高精度);
位置请求设置间隔(300);
位置请求。设置最小位移(1);
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.M)
{
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予和&ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS\u LOCATION)!=PackageManager.permission\u已授予)
ActivityCompat.requestPermissions(MapsActivity.this,新字符串[]{Manifest.permission.ACCESS\u FINE\u LOCATION},REQUEST\u ACCESS);
返回;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest,mlLocationCallback,Looper.myLooper());
}
//这里我们定义了mLocationCallback对象,它在前面的函数中使用。
私有最终位置回调mlLocationCallback=新位置回调(){
@凌驾
public void onLocationResult(LocationResult LocationResult)
{
super.onLocationResult(定位结果);
if(locationResult.getLastLocation()==null)
返回;
currentLocation=locationResult.getLastLocation();
if(firstTimeFlag&&googleMap!=null)
{
animateCamera(当前位置);
firstTimeFlag=true;
}
显示标记(当前位置);
}
};
私有void animateCamera(@NonNull Location)
{
LatLng LatLng=新LatLng(location.getLatitude(),location.getLongitude());
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(getCameraPositionWithBearing(latLng));
}
@非空
专用摄像机位置获取带轴承的摄像机位置(车床){
返回新的CameraPosition.Builder().target(latLng.zoom(16.build));
}
私有void showMarker(@NonNull Location currentLocation)
{
LatLng LatLng=新LatLng(currentLocation.getLatitude(),currentLocation.getLength());
如果(currentLocationMarker==null)
currentLocationMarker=googleMap.addMarker(新标记选项().icon(BitmapDescriptorFactory.defaultMarker()).position(latLng));
其他的
MarkerAnimation.animateMarkerToGB(currentLocationMarker,latLng,new LatlInInterpolator.sphere());
}
}
包com.example.救护车;
导入。。。
公共接口LatLngInterpolator
{
LatLng插值(浮动分数、LatLng a、LatLng b);
类实现LatlInInterpolator
{
/*来自github.com/googlemaps/android-maps-utils*/
@凌驾
公共LatLng插值(浮动分数、LatLng from、LatLng to)
{
//http://en.wikipedia.org/wiki/Slerp
双fromLat=托拉迪安(从纬度);
双fromLng=toRadians(从经度算起);
双托拉特=托拉迪安(至纬度);
双托林=托拉第安(至经度);
双cosFromLat=cos(fromLat);
双cosToLat=cos(toLat);
//计算球面插值系数。
双角度=计算角度(fromLat、fromLng、toLat、toLng);
双正弦角度=正弦(角度);
如果(正弦角度<1E-6)
返乡;
双a=sin((1-分数)*角)/sinAngle;
双b=sin(分数*角度)/sinAngle;
//将极坐标转换为向量并插值。
双x=a*cosFromLat*cos(fromLat)+b*cosToLat*cos(toLng);
双y=a*cosFromLat*sin(fromLng)+b*cosToLat*sin(toLng);
双z=a*sin(fromLat)+b*sin(toLat);
//将插值向量转换回极坐标。
双lat=atan2(z,sqrt(x*x+y*y));
双液化天然气=atan2(y,x);
返回新的LatLng(toDegrees(lat)、toDegrees(lng));
}
私人双倍计程仪(双倍计程仪、双倍计程仪、双倍计程仪、双倍计程仪)
{
//哈弗辛公式
双dLat=fromLat-toLat;
双dLng=从LNG到TOLL;
返回2*asin(sqrt(功率(sin(dLat/2),2)+cos(fromLat)*cos(toLat*pow(sin(dLng/2),2));
}
}
}
包com.e
fusedLocationProviderClient.requestLocationUpdates(locationRequest, mLocationCallback, Looper.myLooper());
private void startLocationUpdates() {
    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(300);
    locationRequest.setSmallestDisplacement(1);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
            ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_ACCESS);
    }
    fusedLocationProviderClient.requestLocationUpdates(locationRequest, mLocationCallback, Looper.myLooper());
}