我在我的应用上使用谷歌地图。我有一个ArrayList,其中包含lat,long和其他信息。我想点击一个标记,然后使用特定的标记信息转到其他Activity
以显示详细信息。
我使用过这段代码,但总是得到ArrayList的最后一个位置。如何获得每个职位的信息?
package com.teledaktar.activities.mapsAndLocation;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.teledaktar.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.Marker;
import com.teledaktar.activities.blogActivities.BlogActivity;
import com.teledaktar.activities.root.MainActivity;
import com.teledaktar.api.AppClient;
import com.teledaktar.api.ApplicationConfig;
import com.teledaktar.model.blog.BlogContent;
import com.teledaktar.model.hospital_model.Hospital;
import com.teledaktar.model.nearestHospitalModels.Hospitals;
import com.teledaktar.model.nearestHospitalModels.NearestHospitalContent;
import com.teledaktar.utility.Constants;
import java.util.ArrayList;
import dmax.dialog.SpotsDialog;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class DoctorLocationOnMapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener, SensorEventListener, GoogleMap.OnMarkerClickListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
Location mLastLocation;
Marker mCurrLocationMarker;
double currentLatitude, currentLongitude;
float mDeclination;
private SpotsDialog pDialog;
private Marker myMarker;
int clickPosition;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_location_on_maps);
pDialog = new SpotsDialog(DoctorLocationOnMapsActivity.this, R.style.Custom);
pDialog.setCancelable(true);
checkLocationPermission();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
//LatLng sydney = new LatLng(-34, 151);
// mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
// mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
buildGoogleApiClient();
if (ActivityCompat.checkSelfPermission(DoctorLocationOnMapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(DoctorLocationOnMapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) {
mMap.setMyLocationEnabled(true);
}
}
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
// mMap.setMyLocationEnabled(true);
return;
}
// Toast.makeText(this, Double.toString(currentLattitude), Toast.LENGTH_SHORT).show();
//specify latitude and longitude of both source and destination
/*Polyline line = googleMap.addPolyline(new PolylineOptions()
.add(new LatLng(currentLattitude, currentLongitude), new LatLng(24.21,88.84))
.width(10)
.color(Color.MAGENTA));
*/
mMap.setOnMarkerClickListener(this);
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
return;
}
String lattitudeString = Constants.latitude;
String longitudeString = Constants.longitude;
if (lattitudeString == null) {
lattitudeString = "23.7277";
}
if (longitudeString == null) {
longitudeString = "90.4106";
}
Double hospitalLat = Double.parseDouble(lattitudeString);
Double hospitalLong = Double.parseDouble(longitudeString);
/*
LatLng bagha = new LatLng(hospitalLat,hospitalLong);
mMap.addMarker(new MarkerOptions().position(bagha).title("Marker in Hospital"));*/
/**
* find current location . latitude and longitude
*/
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation == null) {
Toast.makeText(this, "Please Enable GPS and give location permission to get dirrection ", Toast.LENGTH_SHORT).show();
} else {
currentLatitude = mLastLocation.getLatitude();
currentLongitude = mLastLocation.getLongitude();
getNearestHospitalApiData(currentLatitude, currentLongitude);
/* Polyline line = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(currentLatitude, currentLongitude), new LatLng(hospitalLat, hospitalLong))
.width(10)
.color(Color.GREEN));
*/
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
return;
}
} else {
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
/*
for changing auto rotation
*/
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
float[] rotMat = new float[9];
float[] rotMat1 = new float[9];
SensorManager.getRotationMatrixFromVector(
rotMat, event.values);
float[] orientation = new float[3];
SensorManager.getOrientation(rotMat, orientation);
float bearing = (float) (Math.toDegrees(orientation[0]) + mDeclination);
updateCamera(bearing);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
private void updateCamera(float bearing) {
CameraPosition oldPos = mMap.getCameraPosition();
CameraPosition pos = CameraPosition.builder(oldPos).bearing(bearing).build();
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(pos));
}
public void getNearestHospitalApiData(Double latitude, Double longitude) {
/**
* HERE API CALL WILL BE ADDED
*/
show();
String lats = Double.toString(latitude);
String longs = Double.toString(longitude);
final ApplicationConfig apiServiceReader = AppClient.getApiService();
Call<NearestHospitalContent> list = apiServiceReader.getNearestHospitals(lats, longs);
list.enqueue(new Callback<NearestHospitalContent>() {
@Override
public void onResponse(Call<NearestHospitalContent> call, Response<NearestHospitalContent> response) {
if (response.isSuccessful()) {
hide();
if (response.body().getStatus_code().equals("200")){
ArrayList<Hospitals> nearestHospitals = response.body().getHospitals();
if (nearestHospitals.size() > 0) {
for (int i = 0; i < nearestHospitals.size(); i++) {
Double latitudes = Double.parseDouble(nearestHospitals.get(i).getLatitude().substring(0, 5));
Double longitudes = Double.parseDouble(nearestHospitals.get(i).getLongitude().substring(0, 5));
LatLng hospitalMarker = new LatLng(latitudes, longitudes);
myMarker = mMap.addMarker(new MarkerOptions()
.position(hospitalMarker)
.title(nearestHospitals.get(i).getName())
.snippet(nearestHospitals.get(i).getDescription())
.alpha(0.8f)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
// mMap.addMarker(new MarkerOptions().position(hospitalMarker).title(nearestHospitals.get(i).getName()).alpha(0.8f));
myMarker.showInfoWindow();
Constants.NEAREST_HOSPITAL_NAME = nearestHospitals.get(i).getName();
clickPosition =i;
System.out.println("clicked"+i);
}
}else {
Toast.makeText(DoctorLocationOnMapsActivity.this, "Currently No Nearest Hospital found at this position ", Toast.LENGTH_SHORT).show();
}
}
} else {
hide();
Toast.makeText(DoctorLocationOnMapsActivity.this, "not success", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<NearestHospitalContent> call, Throwable t) {
hide();
Toast.makeText(DoctorLocationOnMapsActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onMarkerClick(final Marker marker) {
Toast.makeText(DoctorLocationOnMapsActivity.this,Integer.toString(clickPosition), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(DoctorLocationOnMapsActivity.this,MainActivity.class);
startActivity(intent);
}
/* Integer clickCount = (Integer) marker.getTag();
if (clickCount != null) {
clickCount = clickCount + 1;
marker.setTag(clickCount);
Toast.makeText(this,
marker.getTitle() +
" has been clicked " + clickCount + " times.",
Toast.LENGTH_SHORT).show();
}*/
return false;
}
private void show() {
pDialog.show();
pDialog.setMessage(getString(R.string.waiting_data_string));
}
private void hide() {
pDialog.dismiss();
}
}