gpt4 book ai didi

java - 如何通过单击按钮获取 GPS 位置?

转载 作者:行者123 更新时间:2023-12-01 15:26:16 24 4
gpt4 key购买 nike

我的项目有一些粗略的代码,我试图在按下按钮时获取用户的 GPS 位置,并且我希望该位置是一个 GeoPoint,然后我可以将其传递给方法。

该方法适用于绘制该点的 Overlay 的 Overlay 类。我正在使用 Stack Overflow 问题 How can I obtain the current GPS location? 中的一些代码。我设置了程序,以便将 GeoPoint 添加到数组中,然后从该数组中检索它并添加到方法中。有没有更好的方法来做到这一点,或者有什么方法可以使用该点而不将其放入数组中?

这是添加 Overlay 并从数组中获取 GeoPoint 的按钮:

Button startBtn = (Button) findViewById(R.id.startBtn);
startBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
getLocation();

tempOverlay = (MapOverlay) listOfOverlays.get(arrayNumber);
tempOverlay.addPoint(points.get(pointCount));
mapView.postInvalidate();
}
}
});

这是创建 locationManager 和 requestUpdates 的 getLocation() 方法。

public void getLocation()
{
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);

System.out.println("Get Location Called");
}

这是 MyLocationListener 类中的 onLocationChanged 方法,用于获取更新,一旦获得位置,我就会停止更新请求。

@Override
public void onLocationChanged(Location loc)
{
if(loc != null)
{
Toast.makeText(getBaseContext(),"LocationChanged : Lat: " + loc.getLatitude()+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
}

p = new GeoPoint((int) (loc.getLatitude() * 1E6),(int) (loc.getLongitude() * 1E6));

points.add(p);
System.out.println("Point Added to Array");

LBServicesActivity.this.lm.removeUpdates(this);

mc.animateTo(p);
mc.setZoom(18);
}

如何将该 GeoPoint 传递给 buttonListener 中的方法而不将其添加到数组中?

最佳答案

创建一个 GPS 类,该类会在位置更改时更新,如下所示:

public class GPSData {
private static double latitude;
/**
* @return the latitude
*/
public static double getLatitude() {
return latitude;
}

/**
* @param latitude the latitude to set
*/
public static void setLatitude(double l) {
latitude = l;
}

private static double longitude;
/**
* @return the longitude
*/
public static double getLongitude() {
return longitude;
}

/**
* @param d the longitude to set
*/
public static void setLongitude(double d) {
longitude = d;
}
}


public static class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
setAccuracy(location.getAccuracy());
setLongitude(location.getLongitude());
setLatitude(location.getLatitude());
}

@Override
public void onProviderDisabled(String provider) {

}

@Override
public void onProviderEnabled(String provider) {

}

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

}
}

然后,当用户单击按钮时,访问该 GPS 类别的值

关于java - 如何通过单击按钮获取 GPS 位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10096376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com