distanceTo(map.getMyLoctation() ) returns null

家住魔仙堡 提交于 2019-12-12 00:45:46

问题


I am new to android and I am using Location manager associated with LocationListener and google maps API v2 and I am trying to get the distance between user''s current Location and another location , but I always get null pointer on map.getMyLocation() .

here is my code :

LocationManager locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
MyLocationListener locListener = new MyLocationListener(this); 
jager =(Button)findViewById(R.id.button1); 
rotebuhlplatz =(Button)findViewById(R.id.button2); 
rotebuhlst =(Button)findViewById(R.id.button3);

if(locListener.canGetLocation ){

    double mLat=locListener.getLatitude();
    double mLong=locListener.getLongitude();

}else{
    // can't get the location
}
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locListener);


map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    Marker jager = map.addMarker(new MarkerOptions().position(DHBWJager56)
        .title("DHBW Jägerstraße 56")
       .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));



    allMarkersMap.put(jager, Jager56.class);
    map.setOnInfoWindowClickListener(this);

    Marker jager2 = map.addMarker(new MarkerOptions().position(DHBWJager58)
        .title("DHBW Jägerstraße 58")
       .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
    allMarkersMap.put(jager, Jager58.class);
    map.setOnInfoWindowClickListener(this);
    Marker rotebuhl = map.addMarker(new MarkerOptions()
        .position(DHBWRotebuhl)
        .title("DHBW Rotebühlplatz 41/1").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
    allMarkersMap.put(rotebuhl, Rotebuhl.class);
    map.setOnInfoWindowClickListener(this);
      //  .icon(BitmapDescriptorFactory
        //    .fromResource(R.drawable.ic_launcher)));

    Marker rts = map.addMarker(new MarkerOptions().position(DHBWRotebuhlstrasse)
            .title("DHBW Rotebühlstraße 131"));
    allMarkersMap.put(rts, SocialWork.class);
    map.setOnInfoWindowClickListener(this);
    // Move the camera instantly to Jagerstrasse with a zoom of 15.
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(DHBWRotebuhl, 17.0f));

    // Zoom in, animating the camera.
    map.animateCamera(CameraUpdateFactory.zoomTo(14), 2000, null);
    map.setMyLocationEnabled(true);
    Location l1=new Location("source");
    l1.setLatitude(DHBWJager56.latitude);
    l1.setLongitude(DHBWJager56.longitude);
    float f=l1.distanceTo(map.getMyLocation());

回答1:


Glad to see you are working with the Google Maps v2 API's.

Here is a link to the GoogleMap documentation. http://developer.android.com/reference/com/google/android/gms/maps/GoogleMap.html

In there you will see that the api for getMyLocation() is deprecated. They recommend you to use LocationClient. Once you get the current location, use the same l1.distanceTo(locationClient.getLastLocation()), and you should be good to go. Hope this helps

Excerpt from documentation:

This method is deprecated. use LocationClient instead. LocationClient provides improved location finding and power usage and is used by the "My Location" blue dot. See the MyLocationDemoActivity in the sample applications folder for example example code, or the Location Developer Guide.

Sample Code they suggest:

public class MyLocationDemoActivity extends FragmentActivity
    implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener {

  private GoogleMap mMap;

  private LocationClient mLocationClient;
  private TextView mMessageView;

  // These settings are the same as the settings for the map. They will in fact give you updates at
  // the maximal rates currently possible.
  private static final LocationRequest REQUEST = LocationRequest.create()
      .setInterval(5000)         // 5 seconds
      .setFastestInterval(16)    // 16ms = 60fps
      .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_location_demo);
    mMessageView = (TextView) findViewById(R.id.message_text);
  }

  @Override
  protected void onResume() {
    super.onResume();
    setUpMapIfNeeded();
    setUpLocationClientIfNeeded();
    mLocationClient.connect();
  }

  @Override
  public void onPause() {
    super.onPause();
    if (mLocationClient != null) {
      mLocationClient.disconnect();
    }
  }

  private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
      // Try to obtain the map from the SupportMapFragment.
      mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
             .getMap();
      // Check if we were successful in obtaining the map.
      if (mMap != null) {
        mMap.setMyLocationEnabled(true);
      }
    }
  }

  private void setUpLocationClientIfNeeded() {
    if (mLocationClient == null) {
      mLocationClient = new LocationClient(
          getApplicationContext(),
          this,  // ConnectionCallbacks
          this); // OnConnectionFailedListener
    }
  }

  /**
   * Button to get current Location. This demonstrates how to get the current Location as required,
   * without needing to register a LocationListener.
   */
  public void showMyLocation(View view) {
    if (mLocationClient != null && mLocationClient.isConnected()) {
      String msg = "Location = " + mLocationClient.getLastLocation();
      Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
    }
  }

  /**
   * Implementation of {@link LocationListener}.
   */
  @Override
  public void onLocationChanged(Location location) {
    mMessageView.setText("Location = " + location);
  }

  /**
   * Callback called when connected to GCore. Implementation of {@link ConnectionCallbacks}.
   */
  @Override
  public void onConnected(Bundle connectionHint) {
    mLocationClient.requestLocationUpdates(
        REQUEST,
        this);  // LocationListener
  }

  /**
   * Callback called when disconnected from GCore. Implementation of {@link ConnectionCallbacks}.
   */
  @Override
  public void onDisconnected() {
    // Do nothing
  }

  /**
   * Implementation of {@link OnConnectionFailedListener}.
   */
  @Override
  public void onConnectionFailed(ConnectionResult result) {
    // Do nothing
  }
}


来源:https://stackoverflow.com/questions/17868534/distancetomap-getmyloctation-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!