distance To(map.getMyLocation())返回null

时间:2013-07-25 20:53:00

标签: android map location

我是Android新手,我正在使用与LocationListener和google maps API v2相关联的位置管理器,我正在尝试获取用户当前位置与另一个位置之间的距离,但我总是在地图上获得空指针。 getMyLocation()。

这是我的代码:

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 个答案:

答案 0 :(得分:2)

很高兴看到您正在使用Google Maps v2 API。

以下是GoogleMap文档的链接。 http://developer.android.com/reference/com/google/android/gms/maps/GoogleMap.html

在那里你会看到不推荐使用getMyLocation()的api。他们建议您使用LocationClient。获得当前位置后,使用相同的l1.distanceTo(locationClient.getLastLocation()),你应该很高兴。希望这有帮助

文件摘录:

  

不推荐使用此方法。请改用LocationClient。       LocationClient提供改进的定位和功率使用,并由       “我的位置”蓝点。请参阅中的MyLocationDemoActivity       示例应用程序文件夹,例如示例代码或Location Developer Guide。

他们建议的示例代码:

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
  }
}