我已经在数据库中存储了经度和纬度的位置,我希望获得所有位置的Latlngs并在Google Map v2上显示它们。
我试图在OnCreate函数中放置一个测试标记,但它不起作用,可能是因为我把它放在错误的地方?
这是我的代码:(代码在没有添加标记的部分的情况下工作):
public class NearbyActivity extends FragmentActivity implements LocationListener,OnInfoWindowClickListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener{
private GoogleMap mMap;
private LocationManager locationManager;
private SupportMapFragment mapFragment;
private GoogleMap map;
private LocationClient mLocationClient;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
// Define a DialogFragment that displays the error dialog
public static class ErrorDialogFragment extends DialogFragment {
// Global field to contain the error dialog
private Dialog mDialog;
// Default constructor. Sets the dialog field to null
public ErrorDialogFragment() {
super();
mDialog = null;
}
// Set the dialog to display
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
// Return a Dialog to the DialogFragment.
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby);
mLocationClient = new LocationClient(this, this, this);
mapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
map = mapFragment.getMap();
map.setMyLocationEnabled(true);
// This is working byt with fixed values not from database..
Marker melbourne = map.addMarker(new MarkerOptions()
.position(new LatLng(26.2412591, 50.5961323))
.title("0000")
.snippet("Manama Capital of Arab Tourism")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.palace)));
onInfoWindowClick(melbourne);
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
Intent intent = new Intent(NearbyActivity.this,Description.class);
intent.putExtra("id", "klkl");
startActivity(intent);
} });
// end of add marker.
}
@Override
protected void onStart() {
super.onStart();
// Connect the client.
if(isGooglePlayServicesAvailable()){
mLocationClient.connect();
}
}
/*
* Called when the Activity is no longer visible.
*/
@Override
protected void onStop() {
// Disconnecting the client invalidates it.
mLocationClient.disconnect();
super.onStop();
}
/*
* Handle results returned to the FragmentActivity
* by Google Play services
*/
@Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
// Decide what to do based on the original request code
switch (requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST:
/*
* If the result code is Activity.RESULT_OK, try
* to connect again
*/
switch (resultCode) {
case Activity.RESULT_OK:
mLocationClient.connect();
break;
}
}
}
private boolean isGooglePlayServicesAvailable() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
// In debug mode, log the status
Log.d("Location Updates", "Google Play services is available.");
return true;
} else {
// Get the error dialog from Google Play services
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog( resultCode,
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null) {
// Create a new DialogFragment for the error dialog
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
errorFragment.setDialog(errorDialog);
errorFragment.show(getSupportFragmentManager(), "Location Updates");
}
return false;
}
}
/*
* Called by Location Services when the request to connect the
* client finishes successfully. At this point, you can
* request the current location or start periodic updates
*/
@Override
public void onConnected(Bundle dataBundle) {
// Display the connection status
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
Location location = mLocationClient.getLastLocation();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17);
map.animateCamera(cameraUpdate);
}
/*
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
@Override
public void onDisconnected() {
// Display the connection status
Toast.makeText(this, "Disconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
/*
* Called by Location Services if the attempt to
* Location Services fails.
*/
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Sorry. Location services not available to you", 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.nearby, menu);
return true;
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 15);
mMap.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
}
@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
}
@Override
public void onInfoWindowClick(Marker arg0) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:0)
尝试在onResume()中添加标记。我很惊讶你没有在map.setMyLocationEnabled(true)上得到空指针异常,因为根据我的经验,地图片段中的地图直到onStart才会被实例化。因此,您无法在onCreate()中为其添加标记。
答案 1 :(得分:0)
首先,您需要将所有数据库值都添加到列表中:例如,具有纬度和经度的商店列表。然后你必须以这种方式将每个标记添加到地图中(下面的代码也处理点击):
private final void addLocationsToMap() {
int i = 0;
for (Stores store : storeList) {
LatLng l = new LatLng(store.getLatitude(), store.getLongtitude());
MarkerOptions marker = new MarkerOptions()
.position(l)
.title(store.getStoreName())
.snippet("" + i)
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
googleMap.addMarker(marker);
++i;
}
googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
try {
popUpWindow.setVisibility(View.VISIBLE);
Stores store = storeList.get(Integer.parseInt(marker
.getSnippet()));
// set details
email.setText(store.getEmail());
phoneNo.setText(store.getPhone());
address.setText(store.getAddress());
// setting test value to phone number
tempString = store.getPhone();
SpannableString spanString = new SpannableString(tempString);
spanString.setSpan(new UnderlineSpan(), 0,
spanString.length(), 0);
phoneNo.setText(spanString);
// setting test value to email
tempStringemail = store.getEmail();
SpannableString spanString1 = new SpannableString(tempStringemail);
spanString1.setSpan(new UnderlineSpan(), 0, spanString1.length(), 0);
email.setText(spanString1);
storeLat = store.getLatitude();
storelng = store.getLongtitude();
} catch (ArrayIndexOutOfBoundsException e) {
Log.e("ArrayIndexOutOfBoundsException", " Occured");
}
}
});
}
答案 2 :(得分:0)
你应该在onResume()中绘制标记,你必须确保在操作之前检查地图!= null。