我是编程新手,正在学习google location api教程。我已经正确地遵循了所有步骤,但是,下面的代码在getLatitude()和getLongitude()处给出了错误信息。错误:无法解析方法getLatitude()。如果有人能指出这个问题,那就太好了。还有一点需要注意的是,代码似乎从来没有使用过android.location.location类,我希望getLatitude()会从那里来。
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationServices;
import android.location.Location;
public class MainActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener {
protected GoogleApiClient mGoogleApiClient;
/**
* Represents a geographical location.
*/
protected String mLastLocation;
protected static final String TAG = "basic-location-sample";
protected TextView mLatitudeText;
protected TextView mLongitudeText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLatitudeText = (TextView) findViewById((R.id.latitude_text));
mLongitudeText = (TextView) findViewById((R.id.longitude_text));
buildGoogleApiClient();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener((OnConnectionFailedListener) this)
.addApi(LocationServices.API)
.build();
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
@Override
public void onConnected(Bundle connectionHint) {
mLastLocation = String.valueOf(LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient));
if (mLastLocation!= null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
@Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
}
最佳答案
看看mLastLocation
的类型:
protected String mLastLocation;
String
没有getLatitude
和getLongitude
方法。变量的类型应为Location
,并且在不调用String.valueOf
的情况下初始化:protected Location mLastLocation;
...
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);