1

I am new to android working on google map and google places api. have been searching from almost last one month. but i am not success. i m developing an app where anyone can find nearest hospitals/laboratories from his/her location. please help me to identify the problem. i'll be grateful.

Here is my manifest

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

<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality. 
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="in.wptrafficanalyzer.locationgeocodingv2.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<uses-permission android:name="com.javapapers.android.googleplacesdetail.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />
<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="@string/google_maps_key" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <!--
         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="@string/google_maps_key" />

    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

This is my Main MapsActivity

public class MapsActivity extends FragmentActivity implements LocationListener {

private static final String GOOGLE_API_KEY = "AIzaSyAVpSjjJ_1PBMsX1phEyzQ6ExwvW3-5PwM";
GoogleMap googleMap;
double latitude = 0;
double longitude = 0;
EditText placeText;
private int PROXIMITY_RADIUS = 5000;

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

    //show error dialog if GoolglePlayServices not available
    if (!isGooglePlayServicesAvailable()) {
        finish();
    }
    setContentView(R.layout.activity_maps);

    placeText = (EditText) findViewById(R.id.actv_Search);
    Button btn_find = (Button) findViewById(R.id.btn_find);
    SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    googleMap = fragment.getMap();
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    googleMap.setMyLocationEnabled(true);
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, true);
    Location location = locationManager.getLastKnownLocation(bestProvider);
    if (location != null) {
        onLocationChanged(location);
    }
    locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);

    btn_find.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            String type = placeText.getText().toString();
            StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
            googlePlacesUrl.append("location=" + latitude + "," + longitude);
            googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
            googlePlacesUrl.append("&types=" + type);
            googlePlacesUrl.append("&sensor=true");
            googlePlacesUrl.append("&key=" + GOOGLE_API_KEY);

            GooglePlacesReadTask googlePlacesReadTask = new GooglePlacesReadTask();
            Object[] toPass = new Object[2];
            toPass[0] = googleMap;
            toPass[1] = googlePlacesUrl.toString();
            googlePlacesReadTask.execute(toPass);
        }
    });
}

private boolean isGooglePlayServicesAvailable() {
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (ConnectionResult.SUCCESS == status) {
        return true;
    } else {
        GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
        return false;
    }
}


@Override
public void onLocationChanged(Location location) {
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    LatLng latLng = new LatLng(latitude, longitude);
    googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    googleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub
}
}

this is my GooglePlaceReadTask class

public class GooglePlacesReadTask extends AsyncTask<Object, Integer, String> {
String googlePlacesData = null;
GoogleMap googleMap;

@Override
protected String doInBackground(Object... inputObj) {
    try {
        googleMap = (GoogleMap) inputObj[0];
        String googlePlacesUrl = (String) inputObj[1];
        Http http = new Http();
        googlePlacesData = http.read(googlePlacesUrl);
    } catch (Exception e) {
        Log.d("Google Place Read Task", e.toString());
    }
    return googlePlacesData;
}

@Override
protected void onPostExecute(String result) {
    PlacesDisplayTask placesDisplayTask = new PlacesDisplayTask();
    Object[] toPass = new Object[2];
    toPass[0] = googleMap;
    toPass[1] = result;
    placesDisplayTask.execute(toPass);
}
}

This is Http class

public class Http {

public String read(String httpUrl) throws IOException {
    String httpData = "";
    InputStream inputStream = null;
    HttpURLConnection httpURLConnection = null;
    try {
        URL url = new URL(httpUrl);
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.connect();
        inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuffer stringBuffer = new StringBuffer();
        String line = "";
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line);
        }
        httpData = stringBuffer.toString();
        bufferedReader.close();
    } catch (Exception e) {
        Log.d("Exception - reading Http url", e.toString());
    } finally {
        inputStream.close();
        httpURLConnection.disconnect();
    }
    return httpData;
}
}

This is Places class

public class Places {

public List<HashMap<String, String>> parse(JSONObject jsonObject) {
    JSONArray jsonArray = null;
    try {
        jsonArray = jsonObject.getJSONArray("results");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return getPlaces(jsonArray);
}

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

    for (int i = 0; i < placesCount; i++) {
        try {
            placeMap = getPlace((JSONObject) jsonArray.get(i));
            placesList.add(placeMap);

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

private HashMap<String, String> getPlace(JSONObject googlePlaceJson) {
    HashMap<String, String> googlePlaceMap = new HashMap<String, String>();
    String placeName = "-NA-";
    String vicinity = "-NA-";
    String latitude = "";
    String longitude = "";
    String reference = "";

    try {
        if (!googlePlaceJson.isNull("name")) {
            placeName = googlePlaceJson.getString("name");
        }
        if (!googlePlaceJson.isNull("vicinity")) {
            vicinity = googlePlaceJson.getString("vicinity");
        }
        latitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lat");
        longitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lng");
        reference = googlePlaceJson.getString("reference");
        googlePlaceMap.put("place_name", placeName);
        googlePlaceMap.put("vicinity", vicinity);
        googlePlaceMap.put("lat", latitude);
        googlePlaceMap.put("lng", longitude);
        googlePlaceMap.put("reference", reference);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return googlePlaceMap;
}
}

At last PlacesDisplayTask class

public class PlacesDisplayTask extends AsyncTask>> {

JSONObject googlePlacesJson;
GoogleMap googleMap;

@Override
protected List<HashMap<String, String>> doInBackground(Object... inputObj) {

    List<HashMap<String, String>> googlePlacesList = null;
    Places placeJsonParser = new Places();

    try {
        googleMap = (GoogleMap) inputObj[0];
        googlePlacesJson = new JSONObject((String) inputObj[1]);
        googlePlacesList = placeJsonParser.parse(googlePlacesJson);
    } catch (Exception e) {
        Log.d("Exception", e.toString());
    }
    return googlePlacesList;
}

@Override
protected void onPostExecute(List<HashMap<String, String>> list) {
    googleMap.clear();
    for (int i = 0; i < list.size(); i++) {
        MarkerOptions markerOptions = new MarkerOptions();
        HashMap<String, String> googlePlace = list.get(i);
        double lat = Double.parseDouble(googlePlace.get("lat"));
        double lng = Double.parseDouble(googlePlace.get("lng"));
        String placeName = googlePlace.get("place_name");
        String vicinity = googlePlace.get("vicinity");
        LatLng latLng = new LatLng(lat, lng);
        markerOptions.position(latLng);
        markerOptions.title(placeName + " : " + vicinity);
        googleMap.addMarker(markerOptions);
    }
}
}
Hardik Parmar
  • 712
  • 2
  • 13
  • 28
taha naqvi
  • 145
  • 1
  • 10
  • I have got the answer from this link.http://stackoverflow.com/questions/21933247/this-ip-site-or-mobile-application-is-not-authorized-to-use-this-api-key. The issue was about server key. i was placing my android api key rather than server key – taha naqvi Jul 25 '16 at 19:32
  • guys.. i am getting another issue now. my app works only first time when i run it. if i will modify the classes and try to run it will not work – taha naqvi Jul 26 '16 at 05:48
  • plz help me to identify that issue. i have created another server key and also gave my laptop's ip address while creating server key. and uninstalled app and reinstalled it many times. also cleared cache but now my app is not working when i click on find button nothing happens – taha naqvi Jul 26 '16 at 07:20

0 Answers0