簡體   English   中英

嘗試使用Maps API查找附近的地方時出現FileNotFoundException

[英]FileNotFoundException when trying to find nearby Places with Maps API

我一直在關注一個教程,以便使用Google Maps和Places API創建一個顯示附近地點的應用。 具體來說,我正在嘗試查看附近的餐館或外賣店。 實際上,應用程序顯示地圖片段,但沒有地方顯示為標記。

我嘗試增加半徑值,並將類型更改為此處列出的一些類型: 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);
}
}

謝謝,我很感激任何幫助。

編輯:異常現在已經消失,但標記仍未顯示在地圖上。

看起來您的網址構建器已損壞。 你有:

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]");

這意味着你有兩個 ? jsontypes之間, 沒有 &之間的types=meal_takeawaylocation 修復它是這樣的:

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]");

(注意:只有前兩個sb.append()調用中的更改 - 也刪除了空格)

FWIW,從長遠來看,使用Volley或類似的JSON請求可能會更容易,而不是下載url並單獨解析它。

嘗試刪除api url中位置坐標之間的空格。

您的網址已損壞,您在緯度坐標后面的逗號后面添加了空格。

如果您想抽象場所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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM