尝试使用Maps API查找附近的地方时出现FileNotFoundException

时间:2014-03-13 17:34:54

标签: java android google-maps google-places-api

我一直在关注教程,以便创建一个使用Google Maps和Places API显示附近地点的应用。具体来说,我正在尝试查看附近的餐馆或外卖店。实际上,应用程序显示地图片段,但没有地方显示为标记。

我尝试增加radius值,并将类型更改为此处列出的一些类型:https://developers.google.com/places/documentation/supported_types,但是我得到了相同的FileNotFoundException错误。任何人都可以看到出了什么问题吗?

这是我的LogCat。

03-13 17:21:51.076: E/GooglePlayServicesUtil(13109): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
03-13 17:21:51.436: D/dalvikvm(13109): GC_FOR_ALLOC freed 2262K, 24% free 8393K/10920K, paused 65ms, total 83ms
03-13 17:21:51.536: D/dalvikvm(13109): GC_FOR_ALLOC freed 1339K, 23% free 8409K/10920K, paused 21ms, total 23ms
03-13 17:21:51.586: W/ActivityThread(13109): ClassLoader.loadClass: The class loader returned by Thread.getContextClassLoader() may fail for processes that host multiple applications. You should explicitly specify a context class loader. For example: Thread.setContextClassLoader(getClass().getClassLoader());
03-13 17:21:52.137: D/dalvikvm(13109): GC_FOR_ALLOC freed 739K, 19% free 8928K/10920K, paused 31ms, total 32ms
03-13 17:21:52.387: D/dalvikvm(13109): GC_FOR_ALLOC freed 775K, 18% free 9233K/11192K, paused 18ms, total 19ms
03-13 17:21:52.457: W/SystemClock(13109): time going backwards: prev 232776411235435(ioctl) vs now 232776411021793(ioctl), tid=13531
03-13 17:21:53.308: D/dalvikvm(13109): GC_FOR_ALLOC freed 1516K, 19% free 9496K/11604K, paused 21ms, total 21ms
03-13 17:21:53.619: D/Exception while downloading url(13109): java.io.FileNotFoundException: https://maps.googleapis.com/maps/api/place/nearbysearch/json??types=meal_takeawaylocation=55.94395494, -3.12815476&radius=10000&sensor=true&key=[My API Key]
03-13 17:21:53.629: D/Background Task(13109): java.lang.NullPointerException
03-13 17:21:53.659: D/Exception(13109): java.lang.NullPointerException

这是我的代码:

public class GPSActivity extends FragmentActivity implements LocationListener{

GoogleMap mGoogleMap;
String[] mPlaceType=null;
String[] mPlaceTypeName=null;

double mLatitude=0;
double mLongitude=0;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gps);

    mPlaceType = getResources().getStringArray(R.array.place_type);
    mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);

    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
    if(status!=ConnectionResult.SUCCESS) {
        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();
    } else {
        SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mGoogleMap = fragment.getMap();
        mGoogleMap.setMyLocationEnabled(true);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(provider);

        if (location!=null) {
            onLocationChanged(location);
        }

        locationManager.requestLocationUpdates(provider, 20000, 0, this);

        String type = mPlaceType[0];

        StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
        sb.append("?types=meal_takeaway");
        sb.append("location="+mLatitude+", "+mLongitude);
        sb.append("&radius=10000");
        sb.append("&sensor=true");
        sb.append("&key=[My API Key]");

        PlacesTask placesTask = new PlacesTask();
        placesTask.execute(sb.toString());
    }
}

public void onLocationChanged(Location location) {
    mLatitude = location.getLatitude();
    mLongitude = location.getLongitude();
    LatLng latLng = new LatLng(mLatitude, mLongitude);
    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}

protected void onPostExecute(List<HashMap<String,String>> list) {
    mGoogleMap.clear();
    for (int i=0; i<list.size(); i++) {
        MarkerOptions markerOptions = new MarkerOptions();
        HashMap<String,String> hmPlace = list.get(i);
        double lat = Double.parseDouble(hmPlace.get("lat"));
        double lng = Double.parseDouble(hmPlace.get("lng"));
        String name = hmPlace.get("meal_takeaway");
        String vicinity = hmPlace.get("vicinity");
        LatLng latLng = new LatLng(lat, lng);
        markerOptions.title(name+" : "+vicinity);
        mGoogleMap.addMarker(markerOptions);
    }
}

@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

}
}


class PlacesTask extends AsyncTask<String,Integer,String> {
String data = null;

private String downloadUrl(String strUrl) throws IOException {
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(strUrl);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();
        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 while downloading url", e.toString());
    } finally {
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}

protected String doInBackground(String... url) {
    try {
        data = downloadUrl(url[0]);
    } catch(Exception e) {
        Log.d("Background Task", e.toString());
    }
    return data;
}

protected void onPostExecute(String result) {
    ParserTask parserTask = new ParserTask();
    parserTask.execute(result);
}
}

谢谢,我很感激任何帮助。

修改:异常现已消失,但标记仍未显示在地图上。

3 个答案:

答案 0 :(得分:1)

看起来您的网址构建器已损坏。你有:

StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
        sb.append("?types=meal_takeaway");
        sb.append("location="+mLatitude+", "+mLongitude);
        sb.append("&radius=10000");
        sb.append("&sensor=true");
        sb.append("&key=[My API Key]");

这意味着?json之间两个 types,而{{1>}之间的没有 & 1}}和types=meal_takeaway。像这样修复它:

location

(注意:前两个StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?"); sb.append("types=meal_takeaway"); sb.append("&location="+mLatitude+","+mLongitude); sb.append("&radius=10000"); sb.append("&sensor=true"); sb.append("&key=[My API Key]"); 调用中只有更改 - 也删除了空格)

FWIW,从长远来看,使用Volley或类似的JSON请求可能会更容易,而不是下载url并单独解析它。

答案 1 :(得分:0)

尝试删除api url中位置坐标之间的空格。

答案 2 :(得分:0)

您的网址已损坏,您在纬度坐标后面的逗号后面添加了一个空格。

如果您想抽象场所API处理,我最近开发了一个Java库,它是Place API的1对1映射。到附近的餐馆就像。

GooglePlaces client = new GooglePlaces("apiKey");
List<Place> places = client.getNearbyPlaces(lat, lng, GooglePlaces.MAXIMUM_RESULTS, Param.name("types").value("restaurant"));
for (Place place : places) {
    System.out.println(place.getName());
}

https://github.com/windy1/google-places-api-java