如何在 onMapReady 方法中访问我在 onLocationChanged 中的当前位置?

Posted

技术标签:

【中文标题】如何在 onMapReady 方法中访问我在 onLocationChanged 中的当前位置?【英文标题】:How do I access my current location in onLocationChanged, in onMapReady method? 【发布时间】:2016-12-13 04:47:25 【问题描述】:

我试图在 onMapReady 方法中的 onLocationChanged 方法中访问我的当前位置,但 currentlatlng 返回 null。任何指导都会有所帮助。

代码如下:

public class MapActivity extends FragmentActivity implements OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener,GoogleMap.OnInfoWindowClickListener 

JSONArray jsonArray;
String json_string;
int _id;
String _doctorname;
String _doclat;
String _doclong;
public static LatLng currentlatLng = null;
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
private GoogleMap mMap;

Location mLastLocation;
Marker mCurrLocationMarker;

Location _location;
MarkerOptions _markeroption;
@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
   // int x =_st.jsonArray.length();
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
        checkLocationPermission();
    

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);



@Override
public void onMapReady(GoogleMap googleMap) 
//Get Last Known Location and convert into Current Longitute and Latitude
//        final LocationManager mlocManager = (LocationManager)    this.getSystemService(Context.LOCATION_SERVICE);
//        final Location currentGeoLocation = mlocManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//
//        double currentLat = currentGeoLocation.getLatitude();
//        double currentLon = currentGeoLocation.getLongitude();
//
//        LatLng currentLatLng = new LatLng(currentLat,currentLon);
//Toast.makeText(this,"Cur Lat" +currentLat+"Lon"+currentLon,Toast.LENGTH_LONG).show();

    // Get JSON String and Break it down into individual nodes
    //double x=_location.getLatitude();
    //double y=_location.getLongitude();
    json_string = getIntent().getExtras().getString("JSON_DTA");
    LatLng latLng = null;
    try 
        int count = 0;
        //jsonObject = new JSONObject(json_string);
        jsonArray = new JSONArray(json_string);

        while (count < jsonArray.length()) 
            JSONObject JO = jsonArray.getJSONObject(count);
            _id = JO.getInt("id");
            _doctorname = JO.getString("doctorname");
            _doclat = JO.getString("latitude");
            _doclong = JO.getString("longitude");

            count++;

            Double d = Double.parseDouble(_doclat);
            Double e = Double.parseDouble(_doclong);
            latLng = new LatLng(d, e);

            DecimalFormat df = new DecimalFormat("####0.0");

            DistanceBetweenPoints distanceBetweenPoints = new DistanceBetweenPoints();
           // double  distance = distanceBetweenPoints.CalculationByDistance(currentLatLng,latLng);

            int distanceThreshHold = 7;
            //if(distance < distanceThreshHold  )
            
                mMap = googleMap;
                MarkerOptions _markeroptions = new MarkerOptions()
                        .position(latLng)
                        .title(_doctorname +  " KM" )
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.gps));

              //  mMap = googleMap;
                mMap.addMarker(_markeroptions);
                mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                mMap.setOnInfoWindowClickListener(this);
            

     


     catch (JSONException e) 
        e.printStackTrace();
    

    //Initialize Google Play Services
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) 
            buildGoogleApiClient();

            mMap.setMyLocationEnabled(true);

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


protected synchronized void buildGoogleApiClient() 
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();

@Override
public void onConnected(@Nullable Bundle bundle) 

    mLocationRequest = new LocationRequest();

    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) 
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    



@Override
public void onConnectionSuspended(int i) 




@Override
public void onLocationChanged(Location location) 

        mLastLocation = location;
        if (mCurrLocationMarker != null) 
            mCurrLocationMarker.remove();
        


        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");

        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mMap.addMarker(markerOptions);


      //  Toast.makeText(this, "Current" + latLng, Toast.LENGTH_LONG).show();
        String tag = null;
        Log.d(tag, "lon: " + location.getLongitude() + " ----- lat: " + location.getLatitude());


        //move map camera
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(11));


        //stop location updates
        if (mGoogleApiClient != null) 
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        


    




@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) 



public boolean checkLocationPermission()
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) 

        // Asking user if explanation is needed
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) 

            // Show an expanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

            //Prompt the user once explanation has been shown
            ActivityCompat.requestPermissions(this,
                    new String[]Manifest.permission.ACCESS_FINE_LOCATION,
                    MY_PERMISSIONS_REQUEST_LOCATION);


         else 
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(this,
                    new String[]Manifest.permission.ACCESS_FINE_LOCATION,
                    MY_PERMISSIONS_REQUEST_LOCATION);
        
        return false;
     else 
        return true;
    

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) 
    switch (requestCode) 
        case MY_PERMISSIONS_REQUEST_LOCATION: 
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) 

                // Permission was granted.
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) 

                    if (mGoogleApiClient == null) 
                        buildGoogleApiClient();
                    
                    mMap.setMyLocationEnabled(true);
                

             else 

                // Permission denied, Disable the functionality that depends on this permission.
                Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
            
            return;
        

        // other 'case' lines to check for other permissions this app might request.
        //You can add here other case statements according to your requirement.
    


@Override
public void onInfoWindowClick(Marker marker) 
    Intent intent = new Intent(MapActivity.this,DoctorAppointment.class);

    startActivity(intent);

也许我错过了一些非常简单的东西。提前谢谢你。

【问题讨论】:

你能检查一下 onLocationChanged 是否真的被调用了吗?否则,currentlatLng 将始终为空。 是的。我的当前位置显示在地图上。 currentlatlng 从未设置。怎么可能不为空? 【参考方案1】:

在 OnLocationChanged 中使用如下所示。

location.getLatitude()
location.getLongtitude()

mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat_own, lng_own), 14));

【讨论】:

我在 OnLocationChanged(latlng 变量)中有我当前的位置。我在方法 onMapReady 中需要这个值,我称之为 'DistanceBetweenPoints distanceBetweenPoints = new DistanceBetweenPoints();双距离 = distanceBetweenPoints.CalculationByDistance(currentlatLng,latLng);' 您可以创建一个具有两个参数 lat long 的方法并从 OnLocationChanged 发送,然后从 onMapReady 获取该值并计算距离。另一种方法是在字段中声明位置并执行获取距离的过程。 我创建了一个方法 public String getCurrentLocation(LatLng latLng) return String.valueOf(latLng);并通过调用 getCurrentLocation(latLng); 传递当前位置的值;在 OnLocationChanged 方法中。在 onMapReady 我试图通过 LatLng abc = null; 访问它字符串 a =getCurrentLocation(abc);但 abc 仍然为空 我已经更新了问题中的代码。在调试时,我确实在 getCurrentLocation() 中获得了我的当前位置,但在 onMapReady 中无法访问它。获取 null/ 就像这样,在字段级别声明位置并轻松获得 lat long。是的,有时它需要时间来获取位置。您可以在访问位置之前添加条件(位置!= null)。和

以上是关于如何在 onMapReady 方法中访问我在 onLocationChanged 中的当前位置?的主要内容,如果未能解决你的问题,请参考以下文章

FragmentContainerView 中未调用/显示 OnMapReady

如何将我的 Firebase 数据库坐标传递给 onMapReady? [关闭]

如何在 ruby​​ on rails 中更改路线?

我在 onStart() 方法上得到地图对象 null

即使地图显示没有任何错误,onMapReady 也不会调用

Map Fragment(Kotlin)onMapReady无法正常工作