Android | Google地图获取当前位置和更新

时间:2015-02-27 20:01:34

标签: android google-maps

我正在尝试将我当前的位置放在地图上并在移动时更新它。每当更新发生时,我想获得当前的longtidude和latitute值以用于其他方法。

private LocationRequest request = LocationRequest.create().setInterval(50000);

我想我必须使用LocationRequest。我创建了一个每5分钟更新一次位置的对象。但现在我不知道如何使用它。我在互联网上查了教程,但对于初学者来说它们是如此复杂。有人有简单的解决方案吗?

修改

这就是我的代码现在的样子:

public class MainActivity extends Activity implements LocationListener {

private GoogleMap map;
public double latitude;
public double longitude;
private LocationManager locationManager;
private Context mContext;
private android.location.LocationListener locationListener;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ;

    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    map.setMyLocationEnabled(true);


    getLocation();
    Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}


@Override
public void onLocationChanged(Location location) {

    if (location != null) {

        longitude = location.getLongitude();

        latitude = location.getLatitude();


        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

    }

}

public void getLocation()
{

    locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

}

}

当我尝试测试时,我的应用程序停止了工作。由于这是我的第一个Android应用程序,我不是很擅长,我无法找到什么错误。

3 个答案:

答案 0 :(得分:1)

用于位置使用此

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

// Define a listener that responds to location updates

locationListener = new LocationListener() {

        public void onLocationChanged(Location location) {

                // Called when a new location is found by the network location provider.

                longitude = String.valueOf(location.getLongitude());

                latitude = String.valueOf(location.getLatitude());

                Log.d(TAG, "changed Loc : " + longitude + ":" + latitude);

        }

        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        public void onProviderEnabled(String provider) {

        }

        public void onProviderDisabled(String provider) {

        }

};

// getting GPS status

isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

// check if GPS enabled

if (isGPSEnabled) {

        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (location != null) {

                longitude = String.valueOf(location.getLongitude());

                latitude = String.valueOf(location.getLatitude());

                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

        } else {

                location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                if (location != null) {

                        longitude = String.valueOf(location.getLongitude());

                        latitude = String.valueOf(location.getLatitude());

                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

                } else {

                        longitude = "0.00";

                        latitude = "0.00";

                }

        }

}

来自http://androidadvance.com/android_snippets.php#h.r43fot3suy6h

答案 1 :(得分:1)

使用gps确定位置(longtidude和latitute值)并将其传递给地图

this mainactivity.java for gps 

public class GpsBasicsAndroidExample extends Activity implements LocationListener {

private LocationManager locationManager;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gps_basics_android_example);
    text=(TextView)findViewById(R.id.tv1);

    /********** get Gps location service LocationManager object ***********/
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    /*
      Parameters :
         First(provider)    :  the name of the provider with which to register 
         Second(minTime)    :  the minimum time interval for notifications, in milliseconds. This field is only used as a hint to conserve power, and actual time between location updates may be greater or lesser than this value. 
         Third(minDistance) :  the minimum distance interval for notifications, in meters 
         Fourth(listener)   :  a {#link LocationListener} whose onLocationChanged(Location) method will be called for each location update 
    */

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1,10, this);

    /********* After registration onLocationChanged method called periodically after each 3 sec ***********/
}

/************* Called after each 3 sec **********/
@Override
public void onLocationChanged(Location location) {

    String str = "Latitude: "+location.getLatitude()+" \nLongitude: "+location.getLongitude();
    //Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
    text.setText(str);
}

@Override
public void onProviderDisabled(String provider) {

    /******** Called when User off Gps *********/

    Toast.makeText(getBaseContext(), "Gps turned off ", Toast.LENGTH_LONG).show();
}

@Override
public void onProviderEnabled(String provider) {

    /******** Called when User on Gps  *********/

    Toast.makeText(getBaseContext(), "Gps turned on ", Toast.LENGTH_LONG).show();
}

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

}

}

这适用于地图

main.java

enter code here

公共类MainActivity扩展了FragmentActivity {

GoogleMap mMap;
@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
    final LatLng CIU = new LatLng(35.21843892856462, 33.41662287712097);
    Marker ciu = mMap.addMarker(new MarkerOptions()
                              .position(CIU).title("My Office"));


    final LatLng CIU1 = new LatLng(30.21843892856462, 33.41662287712097);
    Marker ciu1 = mMap.addMarker(new MarkerOptions()
                              .position(CIU1).title("My Second Office"));

    final LatLng CIU2 = new LatLng(30.21843892856462, 30.41662287712097);
    Marker ciu2 = mMap.addMarker(new MarkerOptions()
                              .position(CIU2).title("My thired Office"));



}

}

答案 2 :(得分:1)

以下是您可以做的事情。我会尽量让你这么简单:

  • 使用implements关键字将LocationListener接口添加到扩展活动类。这将强制您覆盖查找当前位置所需的一些方法。

    public class A extends Activity implements LocationListener {}
    
  • 创建一个Location Manager类的实例,它将作为一个钩子来调用Location包中的各种服务和方法。

    private LocationManager locationManager;
    
  • 创建一个类似getLocation()的方法,并从Location Manger实例调用预定义的服务方法。

    locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);
    
  • 在onLocationChanged()方法中,您可以使用getLongitude()和经度使用getLongitude()使用属于Location Manager类的这两个方法来请求纬度。

  • 将这些方法获得的两个值存储在两个单独的变量中,确保它们是Double类型,稍后您可以将它们转换为String类型,然后在应用程序活动的Text视图中显示它们。

    if (location != null) {
    
                        longitude = String.valueOf(location.getLongitude());
    
                        latitude = String.valueOf(location.getLatitude());
    
                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    
                }
    
  • 调用onCreate()中的getLocation()方法,并通过TextView或Toast在应用程序屏幕上显示它们。

    Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
    
  • 最后但并非最不要忘记在Manifest文件中添加权限。

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

有关详细信息,请参阅此link