Skip to content Skip to sidebar Skip to footer

Mapactivity Query For Nearest Hospital/restaurant Not Working

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 a

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

publicclassMapsActivity2extendsAppCompatActivityimplementsOnMapReadyCallback
{
    private GoogleMap mGoogleMap;
    SupportMapFragment mapFrag;

    @OverrideprotectedvoidonCreate(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);

    }

    @OverridepublicvoidonMapReady(GoogleMap googleMap)
    {
        mGoogleMap=googleMap;
        mGoogleMap.setMyLocationEnabled(true);
        StringBuildersbValue=newStringBuilder(sbMethod());
        PlacesTaskplacesTask=newPlacesTask();
        placesTask.execute(sbValue.toString());
    }

    public StringBuilder sbMethod()
    {

        //use your current location heredoublemLatitude=37.77657;
        doublemLongitude= -122.417506;

        StringBuildersb=newStringBuilder("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;
    }

    privateclassPlacesTaskextendsAsyncTask<String, Integer, String>
    {

        Stringdata=null;

        // Invoked by execute() method of this object@Overrideprotected 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@OverrideprotectedvoidonPostExecute(String result) {
            ParserTaskparserTask=newParserTask();

            // 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
    {
        Stringdata="";
        InputStreamiStream=null;
        HttpURLConnectionurlConnection=null;
        try {
            URLurl=newURL(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();

            BufferedReaderbr=newBufferedReader(newInputStreamReader(iStream));

            StringBuffersb=newStringBuffer();

            Stringline="";
            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;
    }

    privateclassParserTaskextendsAsyncTask<String, Integer, List<HashMap<String, String>>> {

        JSONObject jObject;

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

            List<HashMap<String, String>> places = null;
            Place_JSONplaceJson=newPlace_JSON();

            try {
                jObject = newJSONObject(jsonData[0]);

                places = placeJson.parse(jObject);

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

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

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

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

                // Creating a markerMarkerOptionsmarkerOptions=newMarkerOptions();

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


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

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

                // Getting nameStringname= hmPlace.get("place_name");

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

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

                LatLnglatLng=newLatLng(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 positionMarkerm= mGoogleMap.addMarker(markerOptions);

            }
        }
    }
    publicclassPlace_JSON {

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

            JSONArrayjPlaces=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) {
            intplacesCount= jPlaces.length();
            List<HashMap<String, String>> placesList = newArrayList<HashMap<String, String>>();
            HashMap<String, String> place = null;

            /** Taking each place, parses and adds to list object */for (inti=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 = newHashMap<String, String>();
            StringplaceName="-NA-";
            Stringvicinity="-NA-";
            Stringlatitude="";
            Stringlongitude="";
            Stringreference="";

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

                // Extracting Place Vicinity, if availableif (!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"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"><fragmentxmlns: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:

enter image description here

Post a Comment for "Mapactivity Query For Nearest Hospital/restaurant Not Working"