distanceTo(map.getMyLoctation())返回null [英] distanceTo(map.getMyLoctation() ) returns null

查看:223
本文介绍了distanceTo(map.getMyLoctation())返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Andr​​oid和我使用​​与LocationListener的和谷歌地图API第2版相关联的位置经理,我想获得用户的当前位置,另一个位置之间的距离,但我总是在地图上的空指针。 getMyLocation()。

这是我的code:

 的LocationManager locManager =(的LocationManager)getSystemService(Context.LOCATION_SERVICE);
MyLocationListener locListener =新MyLocationListener(本);
雅格=(按钮)findViewById(R.id.button1);
rotebuhlplatz =(按钮)findViewById(R.id.button2);
rotebuhlst =(按钮)findViewById(R.id.button3);如果(locListener.canGetLocation){    双MLAT = locListener.getLatitude();
    双mLong = locListener.getLongitude();}其他{
    //无法获取位置
}
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locListener);
地图=((MapFragment)getFragmentManager()findFragmentById(R.id.map)。)的GetMap();
    标记雅格= map.addMarker(新的MarkerOptions()位置(DHBWJager56)
        .title伪(DHBWJägerstraße大街56)
       .icon(BitmapDesc​​riptorFactory.defaultMarker(BitmapDesc​​riptorFactory.HUE_GREEN)));    allMarkersMap.put(雅格,Jager56.class);
    map.setOnInfoWindowClickListener(本);    标记jager2 = map.addMarker(新的MarkerOptions()位置(DHBWJager58)
        .title伪(DHBWJägerstraße大街58)
       .icon(BitmapDesc​​riptorFactory.defaultMarker(BitmapDesc​​riptorFactory.HUE_GREEN)));
    allMarkersMap.put(雅格,Jager58.class);
    map.setOnInfoWindowClickListener(本);
    标记rotebuhl = map.addMarker(新的MarkerOptions()
        .POSITION(DHBWRotebuhl)
        .title伪(DHBWRotebühlplatz41/1)图标(BitmapDesc​​riptorFactory.defaultMarker(BitmapDesc​​riptorFactory.HUE_AZURE)))。
    allMarkersMap.put(rotebuhl,Rotebuhl.class);
    map.setOnInfoWindowClickListener(本);
      // .icon(BitmapDesc​​riptorFactory
        // .fromResource(R.drawable.ic_launcher)));    标记RTS = map.addMarker(新的MarkerOptions()位置(DHBWRotebuhlstrasse)
            .title伪(DHBWRotebühlstraße131));
    allMarkersMap.put(RTS,SocialWork.class);
    map.setOnInfoWindowClickListener(本);
    //瞬间移动相机Jägerstraße大街为15的缩放。
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(DHBWRotebuhl,17.0f));    //放大,动画摄像机。
    map.animateCamera(CameraUpdateFactory.zoomTo(14),2000,NULL);
    map.setMyLocationEnabled(真);
    位置L1 =新的位置(源);
    l1.setLatitude(DHBWJager56.latitude);
    l1.setLongitude(DHBWJager56.longitude);
    浮F = l1.distanceTo(map.getMyLocation());


解决方案

很高兴见到您正在使用谷歌地图API V2的工作。

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

在那里你会看到,getMyLocation()API是pcated德$ P $。他们建议您使用LocationClient。一旦你的当前位置,使用相同的l1.distanceTo(locationClient.getLastLocation()),你应该是好去。希望这有助于

从文件摘录:


  

这方法去precated。使用LocationClient来代替。
      LocationClient提供了改进的位置,发现和功耗,并通过使用
      我的位置蓝点。看到的MyLocationDemoActivity
      示例应用程序文件夹,例如例如code或位置开发人员指南。


样code他们建议:

 公共类MyLocationDemoActivity扩展FragmentActivity
    实现ConnectionCallbacks,OnConnectionFailedListener,LocationListener的{  私人GoogleMap的MMAP;  私人LocationClient mLocationClient;
  私人TextView的mMessageView;  //这些设置是相同的地图的设定。他们在实际上给你在更新
  //最大速率目前可能。
  私有静态最终LocationRequest REQUEST = LocationRequest.create()
      .setInterval(5000)//5秒
      .setFastestInterval(16)// 16毫秒= 60fps的
      .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);  @覆盖
  保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.my_location_demo);
    mMessageView =(的TextView)findViewById(R.id.message_text);
  }  @覆盖
  保护无效onResume(){
    super.onResume();
    setUpMapIfNeeded();
    setUpLocationClientIfNeeded();
    mLocationClient.connect();
  }  @覆盖
  公共无效的onPause(){
    super.onPause();
    如果(mLocationClient!= NULL){
      mLocationClient.disconnect();
    }
  }  setUpMapIfNeeded私人无效(){
    //做一个空检查确认,我们还没有实例化地图。
    如果(MMAP == NULL){
      //尝试获取来自SupportMapFragment地图。
      MMAP =((SupportMapFragment)getSupportFragmentManager()。findFragmentById(R.id.map))
             .getMap();
      //检查是否成功地获得地图。
      如果(MMAP!= NULL){
        mMap.setMyLocationEnabled(真);
      }
    }
  }  setUpLocationClientIfNeeded私人无效(){
    如果(mLocationClient == NULL){
      mLocationClient =新LocationClient(
          getApplicationContext(),
          对此,// ConnectionCallbacks
          这个); // OnConnectionFailedListener
    }
  }  / **
   *按钮来获取当前位置。这展示了如何根据需要获取当前位置,
   *无需注册LocationListener的。
   * /
  公共无效showMyLocation(查看视图){
    如果(mLocationClient =空&放大器;!&放大器; mLocationClient.isConnected()){
      弦乐味精=位置=+ mLocationClient.getLastLocation();
      Toast.makeText(getApplicationContext(),味精,Toast.LENGTH_SHORT).show();
    }
  }  / **
   * {@link LocationListener的}的实现。
   * /
  @覆盖
  公共无效onLocationChanged(地点){
    mMessageView.setText(位置=+位置);
  }  / **
   *回调,当连接到命令gcore调用。 {@link ConnectionCallbacks}的实现。
   * /
  @覆盖
  公共无效onConnected(捆绑connectionHint){
    mLocationClient.requestLocationUpdates(
        请求,
        这个); // LocationListener的
  }  / **
   *回调从断开的gcore时调用。 {@link ConnectionCallbacks}的实现。
   * /
  @覆盖
  公共无效onDisconnected(){
    // 没做什么
  }  / **
   * {的@link OnConnectionFailedListener}实现。
   * /
  @覆盖
  公共无效onConnectionFailed(ConnectionResult结果){
    // 没做什么
  }
}

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());

解决方案

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

这篇关于distanceTo(map.getMyLoctation())返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆