1

Hi I have developed an android app which uses google places api to display the nearby locations.

Now when I click on a place name I want to display its location in the map. My question is that how to pass the latitude and longitude to the google maps to be displayed. Right now I am passing the values statically but when I click on the name I want to pass its lat and long dynamically to be drawn. Please tell me how to do that. I am new to android.

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) {
            }
        };

1 Answers1

1

Try this one:

Add itemizedOverlay class:

public class AndroidGoogleMapsActivity extends MapActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Displaying Zooming controls
        MapView mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);


        MapController mc = mapView.getController();
        double lat = Double.parseDouble("48.85827758964043");
        double lon = Double.parseDouble("2.294543981552124");
        GeoPoint geoPoint = new GeoPoint((int)(lat * 1E6), (int)(lon * 1E6));
        mc.animateTo(geoPoint);
        mc.setZoom(15);
        mapView.invalidate(); 


        /**
         * Placing Marker
         * */
        List<Overlay> mapOverlays = mapView.getOverlays();
        Drawable drawable = this.getResources().getDrawable(R.drawable.mark_red);
        AddItemizedOverlay itemizedOverlay = 
             new AddItemizedOverlay(drawable, this);


        OverlayItem overlayitem = new OverlayItem(geoPoint, "Hello", "Sample Overlay item");

        itemizedOverlay.addOverlay(overlayitem);
        mapOverlays.add(itemizedOverlay);

    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}
Yogesh Tatwal
  • 2,722
  • 20
  • 43
  • if you are facing problem than please post your code and prefer this [link](http://stackoverflow.com/questions/5914283/draw-a-path-following-your-location-on-google-maps-for-android) – Yogesh Tatwal Feb 11 '13 at 04:54
  • aren't you passing the lat long statically here? I want to pass it upon a click. in my app I am using google places api to display the details of the place ie; name address phone num and lat long which I want to pass to the map activity to be drawn. –  Feb 11 '13 at 04:56
  • I don't want to pass it statically what I want is that when I click on the name of the place I want to pass the value of the lat and long which I am displaying there to a new activity where I display the map. –  Feb 11 '13 at 05:04
  • After click on places you will get lat and long just pass them in this activity – Yogesh Tatwal Feb 11 '13 at 05:06
  • How to pass it I am new to android can you please tell me how to pass the value and how to use it here? –  Feb 11 '13 at 05:18
  • String str = "My Data"; //Data you want to send Intent intent = new Intent(FirstActivity.this, SecondActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("name",str); //here you will add the data into intent to pass bw activites v.getContext().startActivity(intent); in you another activity String name = this.getIntent().getStringExtra("name"); – Yogesh Tatwal Feb 11 '13 at 05:20
  • here is the link please prefer it [click](http://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android) – Yogesh Tatwal Feb 11 '13 at 05:22
  • myIntent.putExtra("latitude", latitude); Hi I did this but it is asking me to set latitude as final but when I set it as final I get error here asking me to remove the final modifier String latitude = Double.toString(placeDetails.result.geometry.location.lat); –  Feb 11 '13 at 05:26
  • can yo post your complete code and you can not make it final because final value can not be change. – Yogesh Tatwal Feb 11 '13 at 05:31
  • please post also DispMap.class – Yogesh Tatwal Feb 11 '13 at 05:37
  • I am still modifying that can you tell me why I am asked to display it as final I don't think DispMap.class is imp to tell that right. –  Feb 11 '13 at 05:41
  • yes please post your DispMap.class because i think it is working fine – Yogesh Tatwal Feb 11 '13 at 05:55
  • added it please check and let me know. –  Feb 11 '13 at 05:58
  • String coordinates[] =new String[2]; coordinates={latitude,longitude}; – Yogesh Tatwal Feb 11 '13 at 06:03