MapActivity query for nearest hospital/restaurant

2020-02-01 06:22发布

问题:

EDIT: Resolved! In addition to Daniel's answer (saved my life), here's what I did:
1. Replaced the 'MapActivity2' class to a server API key.
2. Let the other keys in the manifest and 'maps_activites.xml. be the android API key
3. Enable the following APIS on Google Developer APIS:
Google Maps Android API
Google Places API for Android
Google Places API Web Service

4. BOOM! It worked. Here's the code to my github repository in any case: https://github.com/bholagabbar/AurumHealthApp
I am trying to retrieve the nearest restaurants from my current location. I am using the code I found online here. However I get the following error. I have placed the entire logcat for the execution and have highlighted the errors in bold:

11-30 04:53:31.000 25292-25292/? I/art: Late-enabling -Xcheck:jni

11-30 04:53:31.033 25292-25302/? I/art: Debugger is no longer active
<>11-30 04:53:31.100 25292-25311/? I/GMPM: App measurement is starting up
11-30 04:53:31.109 25292-25311/? E/GMPM: getGoogleAppId failed with status: 10
11-30 04:53:31.111 25292-25311/? E/GMPM: Uploading is not possible. App measurement disabled

11-30 04:53:31.125 25292-25314/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true`11-30 04:53:31.135 25292-25292/? D/Atlas: Validating map...
11-30 04:53:31.178 25292-25314/? I/Adreno-EGL: : EGL 1.4 QUALCOMM build: (Ibddc658e36)
11-30 04:53:31.178 25292-25314/? I/Adreno-EGL: OpenGL ES Shader Compiler Version: E031.25.03.04
11-30 04:53:31.178 25292-25314/? I/Adreno-EGL: Build Date: 08/10/15 Mon
11-30 04:53:31.178 25292-25314/? I/Adreno-EGL: Local Branch: workspace
11-30 04:53:31.178 25292-25314/? I/Adreno-EGL: Remote Branch:
11-30 04:53:31.178 25292-25314/? I/Adreno-EGL: Local Patches:
11-30 04:53:31.178 25292-25314/? I/Adreno-EGL: Reconstruct Branch:
11-30 04:53:31.179 25292-25314/? I/OpenGLRenderer: Initialized EGL, version 1.4
11-30 04:53:31.193 25292-25314/? D/OpenGLRenderer: Enabling debug mode 0
11-30 04:53:32.663 25292-25292/com.iotaconcepts.aurum I/Choreographer: Skipped 37 frames! The application may be doing too much work on its main thread.
11-30 04:53:32.737 25292-25314/com.iotaconcepts.aurum V/RenderScript: Application requested CPU execution
11-30 04:53:32.747 25292-25314/com.iotaconcepts.aurum V/RenderScript: 0xb7f96960 Launching thread(s), CPUs 4
11-30 04:53:36.092 25292-25292/com.iotaconcepts.aurum D/AndroidRuntime: Shutting down VM
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: FATAL EXCEPTION: main
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: Process: com.iotaconcepts.aurum, PID: 25292
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.iotaconcepts.aurum/com.iotaconcepts.aurum.MapsActivity2}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at android.app.ActivityThread.access$800(ActivityThread.java:155)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at android.os.Looper.loop(Looper.java:135)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5343)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:702)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at com.iotaconcepts.aurum.MapsActivity2.onCreate(MapsActivity2.java:42)

11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:6010)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at android.app.ActivityThread.access$800(ActivityThread.java:155)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at android.os.Looper.loop(Looper.java:135)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5343)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
11-30 04:53:36.093 25292-25292/com.iotaconcepts.aurum E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:702)

I have been losing my head for the past 2 hours trying to figure our the error but in vain. Here is the code for the activity:

EDIT After the fix, here is the the code

package com.iotaconcepts.aurum;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MapsActivity2 extends AppCompatActivity implements OnMapReadyCallback
{
    private GoogleMap mGoogleMap;
    SupportMapFragment mapFrag;

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

        mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);

    }

    @Override
    public void onMapReady(GoogleMap googleMap)
    {
        mGoogleMap=googleMap;
        mGoogleMap.setMyLocationEnabled(true);
        StringBuilder sbValue = new StringBuilder(sbMethod());
        PlacesTask placesTask = new PlacesTask();
        placesTask.execute(sbValue.toString());
    }

    public StringBuilder sbMethod()
    {

        //use your current location here
        double mLatitude = 37.77657;
        double mLongitude = -122.417506;

        StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
        sb.append("location=" + mLatitude + "," + mLongitude);
        sb.append("&radius=5000");
        sb.append("&types=" + "restaurant");
        sb.append("&sensor=true");

        sb.append("&key=AIza************************");

        Log.d("Map", "url: " + sb.toString());

        return sb;
    }

    private class PlacesTask extends AsyncTask<String, Integer, String>
    {

        String data = null;

        // Invoked by execute() method of this object
        @Override
        protected String doInBackground(String... url) {
            try {
                data = downloadUrl(url[0]);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }

        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(String result) {
            ParserTask parserTask = new ParserTask();

            // Start parsing the Google places in JSON format
            // Invokes the "doInBackground()" method of the class ParserTask
            parserTask.execute(result);
        }
    }

    private String downloadUrl(String strUrl) throws IOException
    {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb = new StringBuffer();

            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            data = sb.toString();

            br.close();

        } catch (Exception e) {
            Log.d("Exception", e.toString());
        } finally {
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

    private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {

        JSONObject jObject;

        // Invoked by execute() method of this object
        @Override
        protected List<HashMap<String, String>> doInBackground(String... jsonData) {

            List<HashMap<String, String>> places = null;
            Place_JSON placeJson = new Place_JSON();

            try {
                jObject = new JSONObject(jsonData[0]);

                places = placeJson.parse(jObject);

            } catch (Exception e) {
                Log.d("Exception", e.toString());
            }
            return places;
        }

        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(List<HashMap<String, String>> list) {

            Log.d("Map", "list size: " + list.size());
            // Clears all the existing markers;
            mGoogleMap.clear();

            for (int i = 0; i < list.size(); i++) {

                // Creating a marker
                MarkerOptions markerOptions = new MarkerOptions();

                // Getting a place from the places list
                HashMap<String, String> hmPlace = list.get(i);


                // Getting latitude of the place
                double lat = Double.parseDouble(hmPlace.get("lat"));

                // Getting longitude of the place
                double lng = Double.parseDouble(hmPlace.get("lng"));

                // Getting name
                String name = hmPlace.get("place_name");

                Log.d("Map", "place: " + name);

                // Getting vicinity
                String vicinity = hmPlace.get("vicinity");

                LatLng latLng = new LatLng(lat, lng);

                // Setting the position for the marker
                markerOptions.position(latLng);

                markerOptions.title(name + " : " + vicinity);

                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));

                // Placing a marker on the touched position
                Marker m = mGoogleMap.addMarker(markerOptions);

            }
        }
    }
    public class Place_JSON {

        /**
         * Receives a JSONObject and returns a list
         */
        public List<HashMap<String, String>> parse(JSONObject jObject) {

            JSONArray jPlaces = null;
            try {
                /** Retrieves all the elements in the 'places' array */
                jPlaces = jObject.getJSONArray("results");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            /** Invoking getPlaces with the array of json object
             * where each json object represent a place
             */
            return getPlaces(jPlaces);
        }

        private List<HashMap<String, String>> getPlaces(JSONArray jPlaces) {
            int placesCount = jPlaces.length();
            List<HashMap<String, String>> placesList = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> place = null;

            /** Taking each place, parses and adds to list object */
            for (int i = 0; i < placesCount; i++) {
                try {
                    /** Call getPlace with place JSON object to parse the place */
                    place = getPlace((JSONObject) jPlaces.get(i));
                    placesList.add(place);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return placesList;
        }

        /**
         * Parsing the Place JSON object
         */
        private HashMap<String, String> getPlace(JSONObject jPlace)
        {

            HashMap<String, String> place = new HashMap<String, String>();
            String placeName = "-NA-";
            String vicinity = "-NA-";
            String latitude = "";
            String longitude = "";
            String reference = "";

            try {
                // Extracting Place name, if available
                if (!jPlace.isNull("name")) {
                    placeName = jPlace.getString("name");
                }

                // Extracting Place Vicinity, if available
                if (!jPlace.isNull("vicinity")) {
                    vicinity = jPlace.getString("vicinity");
                }

                latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
                longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
                reference = jPlace.getString("reference");

                place.put("place_name", placeName);
                place.put("vicinity", vicinity);
                place.put("lat", latitude);
                place.put("lng", longitude);
                place.put("reference", reference);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return place;
        }
    }

}

The XML file is:

        <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical" android:layout_width="match_parent"
              android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              xmlns:map="http://schemas.android.com/apk/res-auto"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:id="@+id/map"
              tools:context="com.iotaconcepts.aurum.MapsActivity2"
              android:name="com.google.android.gms.maps.SupportMapFragment"/>

</LinearLayout>

The Manifest File:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.iotaconcepts.aurum" >

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-library android:name="com.google.android.maps" />

    <!-- uses-permission android:name="android.permission.INTERNET" / -->
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/MyMaterialTheme" >
        <activity
            android:name=".MainActivity"
            android:label="Aurum" >
            <intent-filter>
                <action android:name="android.intent.action.MAINACTIVITY" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".LoginActivity"
            android:label="Aurum"
            android:theme="@style/ColorfulActionBarTheme" >
            <intent-filter>
                <action android:name="android.intent.action.LOGIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Splash"
            android:label="Aurum"
            android:theme="@style/ColorfulActionBarTheme" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Diagnosis"
            android:label="Aurum"
            android:theme="@style/Theme.Transparent" >
            <intent-filter>
                <action android:name="android.intent.action.DIAGNOSIS" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/. 
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIza*************************" />

        <activity
            android:name=".MapsActivity2"
            android:label="@string/title_activity_maps2" >
        </activity>
        <activity android:name=".testactivity" >
        </activity>
    </application>

</manifest>

回答1:

I just ran your code and got it working. It looks like the main issue is that there is a space between key and your api key in the query url.

You also didn't have any code that calls getMapAsync(), so you were not getting a map reference and onMapReady() would not have been called.

Also, be sure to use a Server API key with the Places Web API.

Here is the code that worked for me:

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MapsActivity2 extends AppCompatActivity implements OnMapReadyCallback
{
    private GoogleMap mGoogleMap;
    SupportMapFragment mapFrag;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        //Wrong one:
        //setContentView(R.layout.activity_main);

        //Use this one:
        setContentView(R.layout.activity_maps2);

        mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);

    }

    @Override
    public void onMapReady(GoogleMap googleMap)
    {
        mGoogleMap=googleMap;
        mGoogleMap.setMyLocationEnabled(true);
        StringBuilder sbValue = new StringBuilder(sbMethod());
        PlacesTask placesTask = new PlacesTask();
        placesTask.execute(sbValue.toString());
    }

    public StringBuilder sbMethod()
    {

        //use your current location here
        double mLatitude = 37.77657;
        double mLongitude = -122.417506;

        StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
        sb.append("location=" + mLatitude + "," + mLongitude);
        sb.append("&radius=5000");
        sb.append("&types=" + "restaurant");
        sb.append("&sensor=true");

        sb.append("&key=AIza******************************");

        Log.d("Map", "url: " + sb.toString());

        return sb;
    }

    private class PlacesTask extends AsyncTask<String, Integer, String>
    {

        String data = null;

        // Invoked by execute() method of this object
        @Override
        protected String doInBackground(String... url) {
            try {
                data = downloadUrl(url[0]);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }

        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(String result) {
            ParserTask parserTask = new ParserTask();

            // Start parsing the Google places in JSON format
            // Invokes the "doInBackground()" method of the class ParserTask
            parserTask.execute(result);
        }
    }

    private String downloadUrl(String strUrl) throws IOException
    {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb = new StringBuffer();

            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            data = sb.toString();

            br.close();

        } catch (Exception e) {
            Log.d("Exception", e.toString());
        } finally {
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

    private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {

        JSONObject jObject;

        // Invoked by execute() method of this object
        @Override
        protected List<HashMap<String, String>> doInBackground(String... jsonData) {

            List<HashMap<String, String>> places = null;
            Place_JSON placeJson = new Place_JSON();

            try {
                jObject = new JSONObject(jsonData[0]);

                places = placeJson.parse(jObject);

            } catch (Exception e) {
                Log.d("Exception", e.toString());
            }
            return places;
        }

        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(List<HashMap<String, String>> list) {

            Log.d("Map", "list size: " + list.size());
            // Clears all the existing markers;
            mGoogleMap.clear();

            for (int i = 0; i < list.size(); i++) {

                // Creating a marker
                MarkerOptions markerOptions = new MarkerOptions();

                // Getting a place from the places list
                HashMap<String, String> hmPlace = list.get(i);


                // Getting latitude of the place
                double lat = Double.parseDouble(hmPlace.get("lat"));

                // Getting longitude of the place
                double lng = Double.parseDouble(hmPlace.get("lng"));

                // Getting name
                String name = hmPlace.get("place_name");

                Log.d("Map", "place: " + name);

                // Getting vicinity
                String vicinity = hmPlace.get("vicinity");

                LatLng latLng = new LatLng(lat, lng);

                // Setting the position for the marker
                markerOptions.position(latLng);

                markerOptions.title(name + " : " + vicinity);

                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));

                // Placing a marker on the touched position
                Marker m = mGoogleMap.addMarker(markerOptions);

            }
        }
    }
    public class Place_JSON {

        /**
         * Receives a JSONObject and returns a list
         */
        public List<HashMap<String, String>> parse(JSONObject jObject) {

            JSONArray jPlaces = null;
            try {
                /** Retrieves all the elements in the 'places' array */
                jPlaces = jObject.getJSONArray("results");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            /** Invoking getPlaces with the array of json object
             * where each json object represent a place
             */
            return getPlaces(jPlaces);
        }

        private List<HashMap<String, String>> getPlaces(JSONArray jPlaces) {
            int placesCount = jPlaces.length();
            List<HashMap<String, String>> placesList = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> place = null;

            /** Taking each place, parses and adds to list object */
            for (int i = 0; i < placesCount; i++) {
                try {
                    /** Call getPlace with place JSON object to parse the place */
                    place = getPlace((JSONObject) jPlaces.get(i));
                    placesList.add(place);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return placesList;
        }

        /**
         * Parsing the Place JSON object
         */
        private HashMap<String, String> getPlace(JSONObject jPlace)
        {

            HashMap<String, String> place = new HashMap<String, String>();
            String placeName = "-NA-";
            String vicinity = "-NA-";
            String latitude = "";
            String longitude = "";
            String reference = "";

            try {
                // Extracting Place name, if available
                if (!jPlace.isNull("name")) {
                    placeName = jPlace.getString("name");
                }

                // Extracting Place Vicinity, if available
                if (!jPlace.isNull("vicinity")) {
                    vicinity = jPlace.getString("vicinity");
                }

                latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
                longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
                reference = jPlace.getString("reference");

                place.put("place_name", placeName);
                place.put("vicinity", vicinity);
                place.put("lat", latitude);
                place.put("lng", longitude);
                place.put("reference", reference);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return place;
        }
    }

}

activity_maps2.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map"
        tools:context="com.iotaconcepts.aurum.MapsActivity2"
        android:name="com.google.android.gms.maps.SupportMapFragment"/>

</LinearLayout>

Result: