2011-09-25 80 views
0

我遵循Android的HelloMapView教程,并添加了一些代码来捕获我当前的位置信息并显示在文本视图中。Android MapActivity无法检索位置数据

我已经测试了这些代码在另一个程序中,它的工作,它能够显示我的经度和纬度数据,当启动应用程序。但是,当我将代码复制到此MapActivity中时,似乎我无法获取位置数据。

下面是部分代码:

public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     mapView = (MapView) findViewById(R.id.mapview); 
     mapView.setBuiltInZoomControls(true); 
     mapOverlays = mapView.getOverlays(); 
     drawable = this.getResources().getDrawable(R.drawable.androidmarker); 
     itemizedOverlay = new HelloItemizedOverlay(drawable, this); 
     Button button1 = (Button)this.findViewById(R.id.button1); 
     tv1 = (TextView) this.findViewById(R.id.textView1); 
     button1.setOnClickListener(mScan); 
     latitude = 1.3831625; 
     longitude = 103.7727321; 


     LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
     Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
     if (location == null) 
      location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
     if (location != null) { 
      if (System.currentTimeMillis() - location.getTime() < 3000) 
      { 
       longitude = location.getLongitude(); 
       latitude = location.getLatitude(); 

       tv1.setText(Double.toString(longitude)); 

      } 
     } 
     lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 10, locationListener); 

    } 

    private final LocationListener locationListener = new LocationListener() { 
     public void onLocationChanged(Location location) { 
      longitude = location.getLongitude(); 
      latitude = location.getLatitude(); 

      tv1.setText(Double.toString(latitude)); 
     } 

     @Override 
     public void onProviderDisabled(String provider) { 
      // TODO Auto-generated method stub 

     } 

     @Override 
     public void onProviderEnabled(String provider) { 
      // TODO Auto-generated method stub 

     } 

     @Override 
     public void onStatusChanged(String provider, int status, Bundle extras) { 
      // TODO Auto-generated method stub 

     } 
    }; 
+0

另请注意,即使我已经自定义了经度和纬度,但我的tv1并未更新为任何值。 – phatez

回答

0

你有没有在清单中添加适当的权限?像这样

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

此外请检查您的GPS是启用或工作在你的deive。