こんにちは、Google Places APIを使用して近くの場所を表示するAndroidアプリを開発しました。
場所の名前をクリックすると、その場所が地図に表示されます。私の質問は、緯度と経度をGoogleマップに渡して表示する方法です。現在、値を静的に渡していますが、名前をクリックすると、緯度と経度を動的に渡して描画したいと考えています。その方法を教えてください。私はアンドロイドが初めてです。
public class SinglePlaceActivity extends Activity {
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
// Google Places
GooglePlaces googlePlaces;
// Place Details
PlaceDetails placeDetails;
// Progress dialog
ProgressDialog pDialog;
Button submit;
Button piechart;
TextView error;
// KEY Strings
public static String KEY_REFERENCE = "reference"; // id of the place
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single_place);
Intent i = getIntent();
// Place referece id
String reference = i.getStringExtra(KEY_REFERENCE);
// Calling a Async Background thread
new LoadSinglePlaceDetails().execute(reference);
submit = (Button) findViewById(R.id.submitbutton);
piechart = (Button) findViewById(R.id.piechart);
error = (TextView) findViewById(R.id.list);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(SinglePlaceActivity.this,RecoProd.class);
SinglePlaceActivity.this.startActivity(myIntent);
}
});
piechart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myInt = new Intent(SinglePlaceActivity.this,PieChart.class);
SinglePlaceActivity.this.startActivity(myInt);
}
});
}
/**
* Background Async Task to Load Google places
* */
class LoadSinglePlaceDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SinglePlaceActivity.this);
pDialog.setMessage("Loading profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Profile JSON
* */
protected String doInBackground(String... args) {
String reference = args[0];
// creating Places class object
googlePlaces = new GooglePlaces();
// Check if used is connected to Internet
try {
placeDetails = googlePlaces.getPlaceDetails(reference);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed Places into LISTVIEW
* */
if(placeDetails != null){
String status = placeDetails.status;
// check place deatils status
// Check for all possible status
if(status.equals("OK")){
if (placeDetails.result != null) {
String name = placeDetails.result.name;
String address = placeDetails.result.formatted_address;
String phone = placeDetails.result.formatted_phone_number;
String website = placeDetails.result.formatted_web_site;
String latitude = Double.toString(placeDetails.result.geometry.location.lat);
String longitude = Double.toString(placeDetails.result.geometry.location.lng);
Log.d("Place ", name + address + phone + latitude + longitude + website);
// Displaying all the details in the view
// single_place.xml
TextView lbl_name = (TextView) findViewById(R.id.name);
TextView lbl_address = (TextView) findViewById(R.id.address);
TextView lbl_phone = (TextView) findViewById(R.id.phone);
TextView lbl_website = (TextView) findViewById(R.id.web_site);
TextView lbl_location = (TextView) findViewById(R.id.location);
lbl_name.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(SinglePlaceActivity.this,DispMap.class);
myIntent.putExtra("latitude", "latitude");
myIntent.putExtra("longitude", "longitude");
SinglePlaceActivity.this.startActivity(myIntent);
}
});
// Check for null data from google
// Sometimes place details might missing
name = name == null ? "Not present" : name; // if name is null display as "Not present"
address = address == null ? "Not present" : address;
phone = phone == null ? "Not present" : phone;
website = website == null ? "Not present" : website;
latitude = latitude == null ? "Not present" : latitude;
longitude = longitude == null ? "Not present" : longitude;
lbl_name.setText(name);
lbl_address.setText(address);
lbl_phone.setText(Html.fromHtml("<b>Phone:</b> " + phone));
lbl_website.setText(Html.fromHtml("<b>website:</b> " + website));
lbl_location.setText(Html.fromHtml("<b>Latitude:</b> " + latitude + ", <b>Longitude:</b> " + longitude));
}
}
else if(status.equals("ZERO_RESULTS")){
alert.showAlertDialog(SinglePlaceActivity.this, "Near Places",
"Sorry no place found.",
false);
}
else if(status.equals("UNKNOWN_ERROR"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry unknown error occured.",
false);
}
else if(status.equals("OVER_QUERY_LIMIT"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry query limit to google places is reached",
false);
}
else if(status.equals("REQUEST_DENIED"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured. Request is denied",
false);
}
else if(status.equals("INVALID_REQUEST"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured. Invalid Request",
false);
}
else
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured.",
false);
}
}else{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured.",
false);
}
}
});
}
}
}
DispMap.Class
MapView mapView;
MapController mc;
GeoPoint p;
String longitude,latitude;
public class MapOverlay extends com.google.android.maps.Overlay
{
@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
// TODO Auto-generated method stub
super.draw(canvas, mapView, shadow, when);
//translate the geo points to screen pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
//add the marker
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.hospitalbuilding);
Bitmap bmp1 = BitmapFactory.decodeResource(getResources(), R.drawable.shadow);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50,null);
canvas.drawBitmap(bmp1, screenPts.x, screenPts.y-40,null);
return true;
}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nearbyhospitals);
//database work
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String hospital_name = extras.getString("Hname");
Toast.makeText(getApplicationContext(), hospital_name, Toast.LENGTH_LONG).show();
// fill the lat and long postion here from database or from elsewhere
longitude = "31.44";
latitude = "75.23";
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mc = mapView.getController();
String temp = getCurrentLocation();
try {
} catch (Exception e) {
// TODO: handle exception
}
Toast.makeText(getApplicationContext(), "So here we get:"+latitude+","+longitude, Toast.LENGTH_LONG).show();
String coordinates[] ={"31","71"};
//Toast.makeText(getApplicationContext(), coordinates[0]+","+coordinates[1], Toast.LENGTH_LONG).show();
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint((int)(lat*1E6), (int)(lng*1E6));
mc.animateTo(p);
mc.setZoom(13);
//---Add a location marker---
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public String getCurrentLocation()
{
double latitude, longitude;
LocationManager locManager;
locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f, locationListener);
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
return Double.toString(latitude)+","+Double.toString(longitude);
}
else
return "Location not found please try again";
}
public final LocationListener locationListener = new LocationListener()
{
public void onLocationChanged(Location location)
{
}
public void onProviderDisabled(String provider)
{
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};