DistanceTo运行时崩溃应用程序

时间:2018-04-22 11:22:53

标签: java android

我正在尝试从gps获取2个位置之间的区别,每当我点击按钮转到我的MapsActivity时,我都会遇到此错误

Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference

当我评论检查距离差异的代码它工作正常,我不明白标记选项和DistanceTo之间的连接 这是我的代码(请记住,一切正常,只是DistanceTo不起作用)

locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            //get the latitude and longitude from the location
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            //get the location name from latitude and longitude
            Geocoder geocoder = new Geocoder(getApplicationContext());
            try {
                if(location != null) 
// this gives address list from the maps, not important and commented

                {
                    List<Address> addresses =
                            geocoder.getFromLocation(latitude, longitude, 1);
// Marker options where the issue occurs
                    //String result = addresses.get(0).getSubLocality()+":";
                    //result += addresses.get(0).getLocality()+":";
                    // result += addresses.get(0).getCountryCode();
                    LatLng latLng = new LatLng(latitude, longitude);
                    mMap.addMarker(new MarkerOptions().position(latLng).title("Marker Title"));
                    mMap.setMaxZoomPreference(20);
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
//Where it checks for the locations and the distance between them
            if(LocationA == null) {
                LocationA = location;
            }

            LocationB = location;


            LocationA = LocationB;

            DiffernceInDistance = LocationA.distanceTo(LocationB);

        }

我制作地图的代码

  public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
        if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {


            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);

        }
        else {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);


        }
}

1 个答案:

答案 0 :(得分:0)

问题在于我在寻找位置并同时应用标记,因此标记无法加载到该位置,为了解决它我评论过,它不会再崩溃但是它没有解决我的主要问题(距离没有工作,但这不是我发布这篇文章的原因,因此我不会再要求帮助了谢谢)

mMap.addMarker(new MarkerOptions().position(latLng).title("Marker Title"));