如何传递要在谷歌地图上显示的地方的经纬度?

时间:2013-02-11 04:50:22

标签: android google-maps google-places-api

您好我开发了一个Android应用程序,它使用google places api来显示附近的位置。

现在,当我点击地名时,我想在地图中显示其位置。我的问题是如何将纬度和经度传递给要显示的谷歌地图。现在我静态传递值,但是当我点击名称时,我想动态传递其lat和long来绘制。请告诉我该怎么做。我是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 个答案:

答案 0 :(得分:1)

试试这个:

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