我使用谷歌Places API的第一個再寄一次要顯示附近的公用事業(可以說醫院)在密閉radius.When我點擊「查找按鈕「沒什麼happens.I我使用這個鏈接來開發這個項目:link我已經正確生成谷歌Places API的關鍵,但它總是顯示以下錯誤:谷歌Places API的不working.Authentication未能在服務器上
Authentication failed on the server.
E/Google Maps Android API: Authorization failure. Please see https://developers.google.com/maps/documentation/android/start for how to correctly set up the map.
E/Google Maps Android API: In the Google Developer Console (https://console.developers.google.com) Ensure that the "Google Maps Android API v2" is enabled. Ensure that the following Android Key exists: API Key: AIzaSyA4NL7****************************
Android Application (<cert_fingerprint>;<package_name>): E8:2E:B3:C5:17:B2:20:4D:CD:A6:4A:FF:95:A3:3D:3F:8F:E6:0A:47;com.example.hp.mytask
這裏是我的所有活動和AndroidManifest.xml中:
GooglePlacesActivity.java
public class GooglePlacesActivity extends FragmentActivity implements LocationListener {
private static final String GOOGLE_API_KEY = "AIzaSyA4NL7vvQhIt2vx61ePt4d4TqDAYtZctu8";
GoogleMap googleMap;
EditText placeText;
double latitude = 0;
double longitude = 0;
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_google_places);
placeText = (EditText) findViewById(R.id.placeText);
Button btnFind = (Button) findViewById(R.id.btnFind);
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
googleMap = fragment.getMap();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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);
btnFind.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
}
}
Http.java
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("Excptn-readingHttp url", e.toString());
} finally {
inputStream.close();
httpURLConnection.disconnect();
}
return httpData;
}
}
GooglePlacesReadTask.java
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);
}
}
PlacesDisplayTask.java
public class PlacesDisplayTask extends AsyncTask<Object, Integer, List<HashMap<String, String>>> {
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);
}
}
}
Places.java
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;
}
}
AndroidManifest.xml中
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hp.mytask">
<permission
android:name="com.javapapers.android.googleplacesdetail.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.javapapers.android.googleplacesdetail.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="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name=".GooglePlacesActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyA4NL7vvQhIt2vx61ePt4d4TqDAYtZctu8" />
</application>
</manifest>
這不工作!用'機器人NAME =「com.google.android.geo.API_KEY」': – swapnil
嘗試更換'機器人NAME =「com.google.android.maps.v2.API_KEY」' –
你能夠在開發者控制檯應用程序?另外,進行更改後,請在設備/模擬器上完全重新安裝應用程序。 –