0

I have successfully made an activity that shows nearby places. Now I have to retrieve Maps based on spinner value and show the default world map if no value is selected from the spinner. Say I have a spinner in the action bar of an activity, and it consists of various city names, and if I chose New York from the spinner, the map of New York appears in the Map Screen Area. If possible, can Anyone guide me how to do this and also if possible, tell me how to show the famous tourist locations of that city. I have not found any beneficial tutorial on this. Any help would be appreciated.

My NearbyPlacesActivity.java

public class NearbyPlacesActivity extends Activity implements LocationListener {

    //instance variables for Marker icon drawable resources
    private int userIcon, foodIcon, drinkIcon, shopIcon, otherIcon;

    //the map
    private GoogleMap theMap;

    //location manager
    private LocationManager locMan;

    //gps tracker and connnection detect to be included

    //user marker
    private Marker userMarker;

    //places of interest
    private Marker[] placeMarkers;
    //max
    private final int MAX_PLACES = 20;//most returned from google
    //marker options
    private MarkerOptions[] places;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nearby_places);

        //get drawable IDs
        userIcon = R.drawable.yellow_point;
        foodIcon = R.drawable.red_point;
        drinkIcon = R.drawable.blue_point;
        shopIcon = R.drawable.green_point;
        otherIcon = R.drawable.purple_point;

        //find out if we already have it
        if(theMap==null){
            //get the map
            theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
            //check in case map/ Google Play services not available
            if(theMap!=null){
                //ok - proceed
                theMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                //create marker array
                placeMarkers = new Marker[MAX_PLACES];

            }

        }
    }

    //location listener functions

    @Override
    public void onLocationChanged(Location location) {
        Log.v("MyMapActivity", "location changed");
        updatePlaces(location);
    }
    @Override
    public void onProviderDisabled(String provider){
        Log.v("MyMapActivity", "provider disabled");
    }
    @Override
    public void onProviderEnabled(String provider) {
        Log.v("MyMapActivity", "provider enabled");
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        Log.v("MyMapActivity", "status changed");
    }

    /*
     * update the place markers
     */
    private void updatePlaces(Location givenlocation){
        //get location manager
        double lat = givenlocation.getLatitude();
        double lng = givenlocation.getLongitude();
        //create LatLng
        LatLng lastLatLng = new LatLng(lat, lng);

        //remove any existing marker
        if(userMarker!=null) userMarker.remove();
        //create and set marker properties
        userMarker = theMap.addMarker(new MarkerOptions()
        .position(lastLatLng)
        .title("You are here")
        .icon(BitmapDescriptorFactory.fromResource(userIcon))
        .snippet("Your last recorded location"));
        //move to location
        theMap.animateCamera(CameraUpdateFactory.newLatLng(lastLatLng), 3000, null);

        //build places query string
        @SuppressWarnings("deprecation")
        String encodedstr = URLEncoder.encode("food|bar|movie_theater|museum|bank");
        String placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
                "json?location="+lat+","+lng+
                "&radius=7000&sensor=true"+
                "&types="+encodedstr+
                "&key=AIzaSyBqDgqbxFenOtooTivY5YSsJ2JrwBK42hw";//ADD KEY

        //execute query
        new GetPlaces().execute(placesSearchStr);       
        locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
    }

    private class GetPlaces extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... placesURL) {
            //fetch places

            //build result as string
            StringBuilder placesBuilder = new StringBuilder();
            //process search parameter string(s)
            for (String placeSearchURL : placesURL) {
                HttpClient placesClient = new DefaultHttpClient();
                try {
                    //try to fetch the data

                    //HTTP Get receives URL string
                    HttpGet placesGet = new HttpGet(placeSearchURL);
                    //execute GET with Client - return response
                    HttpResponse placesResponse = placesClient.execute(placesGet);
                    //check response status
                    StatusLine placeSearchStatus = placesResponse.getStatusLine();
                    //only carry on if response is OK
                    if (placeSearchStatus.getStatusCode() == 200) {
                        //get response entity
                        HttpEntity placesEntity = placesResponse.getEntity();
                        //get input stream setup
                        InputStream placesContent = placesEntity.getContent();
                        //create reader
                        InputStreamReader placesInput = new InputStreamReader(placesContent);
                        //use buffered reader to process
                        BufferedReader placesReader = new BufferedReader(placesInput);
                        //read a line at a time, append to string builder
                        String lineIn;
                        while ((lineIn = placesReader.readLine()) != null) {
                            placesBuilder.append(lineIn);
                        }
                    }
                }
                catch(Exception e){ 
                    e.printStackTrace(); 
                }
            }
            return placesBuilder.toString();
        }
        //process data retrieved from doInBackground
        protected void onPostExecute(String result) {
            //parse place data returned from Google Places
            //remove existing markers
            if(placeMarkers!=null){
                for(int pm=0; pm<placeMarkers.length; pm++){
                    if(placeMarkers[pm]!=null)
                        placeMarkers[pm].remove();
                }
            }
            try {
                //parse JSON

                //create JSONObject, pass stinrg returned from doInBackground
                JSONObject resultObject = new JSONObject(result);
                //get "results" array
                JSONArray placesArray = resultObject.getJSONArray("results");
                //marker options for each place returned
                places = new MarkerOptions[placesArray.length()];
                //loop through places
                for (int p=0; p<placesArray.length(); p++) {
                    //parse each place
                    //if any values are missing we won't show the marker
                    boolean missingValue=false;
                    LatLng placeLL=null;
                    String placeName="";
                    String vicinity="";
                    int currIcon = otherIcon;
                    try{
                        //attempt to retrieve place data values
                        missingValue=false;
                        //get place at this index
                        JSONObject placeObject = placesArray.getJSONObject(p);
                        //get location section
                        JSONObject loc = placeObject.getJSONObject("geometry")
                                .getJSONObject("location");
                        //read lat lng
                        placeLL = new LatLng(Double.valueOf(loc.getString("lat")), 
                                Double.valueOf(loc.getString("lng")));  
                        //get types
                        JSONArray types = placeObject.getJSONArray("types");
                        //loop through types
                        for(int t=0; t<types.length(); t++){
                            //what type is it
                            String thisType=types.get(t).toString();
                            //check for particular types - set icons
                            if(thisType.contains("food")){
                                currIcon = foodIcon;
                                break;
                            }
                            else if(thisType.contains("bar")){
                                currIcon = drinkIcon;
                                break;
                            }
                            else if(thisType.contains("movie_theater")){
                                currIcon = shopIcon;
                                break;
                            }
                        }
                        //vicinity
                        vicinity = placeObject.getString("vicinity");
                        //name
                        placeName = placeObject.getString("name");
                    }
                    catch(JSONException jse){
                        Log.v("PLACES", "missing value");
                        missingValue=true;
                        jse.printStackTrace();
                    }
                    //if values missing we don't display
                    if(missingValue)    places[p]=null;
                    else
                        places[p]=new MarkerOptions()
                    .position(placeLL)
                    .title(placeName)
                    .icon(BitmapDescriptorFactory.fromResource(currIcon))
                    .snippet(vicinity);
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            if(places!=null && placeMarkers!=null){
                for(int p=0; p<places.length && p<placeMarkers.length; p++){
                    //will be null if a value was missing
                    if(places[p]!=null)
                        placeMarkers[p]=theMap.addMarker(places[p]);

            }

        }
    }   
}
    @Override
    protected void onResume() {
        super.onResume();
        if(theMap!=null){
            //get location manager
        locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        //get last location
        Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
        updatePlaces(lastLoc);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(theMap!=null){
            locMan.removeUpdates(this);
        }
    }
}
divyang7
  • 309
  • 3
  • 10
  • 22
  • you have to set a marker to the location of your spinner data, and you can use places api to list tourists spots around the selected spot and you can even specify the diameter of your search – Niko Jul 28 '13 at 05:58
  • ohk, and how should I use the spinner in actionBar.. As far as I know I have to implement OnNavigationListener and have to provide ArrayAdapter as first paramater in setNavigationCallbacks method. But how should I populate the spinner...plz can you guide me stepwise as I am just a beginner in android. – divyang7 Jul 28 '13 at 06:04
  • have you checked this http://stackoverflow.com/questions/5999262/populate-spinner-dynamically-in-android-from-edit-text – Niko Jul 28 '13 at 06:11
  • I got how to create spinner in actionbar..now how to implement listner on it..? – divyang7 Jul 28 '13 at 06:12
  • You should not call OnItemClickListener for spinner. You can apply OnItemSelectedListener instead. – Niko Jul 28 '13 at 06:22

1 Answers1

0

This is how, you may implement your spinner listener

yourpinner.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub

        }
    });

you may check this and this for additional reference

Community
  • 1
  • 1
Niko
  • 1,367
  • 1
  • 13
  • 37
  • In a spinner's case, it may work, but I don't think this is the right way to implement a listener to action bar navigation... – divyang7 Jul 28 '13 at 06:41