谷歌地图放置api错误检测位置

时间:2016-02-26 09:56:37

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

我创建了这个脚本,用于抓住我附近的地方。但我有问题,我认为这个问题是得到许可的。 该脚本不会分配我当前的位置和位置。

我在这里发布源代码:

  private void updatePlaces() {
    //get location manager
    locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    //get last location
    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;
    }
    Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    double lat = lastLoc.getLatitude();
    double lng = lastLoc.getLongitude();
    //create LatLng
    LatLng lastLatLng = new LatLng(lat, lng);

    //remove any existing marker
    if (userMarker != null) userMarker.remove();
    //create and set marker properties
    userMarker = theMap.addMarker(new MarkerOptions()
            .position(lastLatLng)
            .title("You are here")
            .icon(BitmapDescriptorFactory.fromResource(userIcon))
            .snippet("Your last recorded location"));
    //move to location
    theMap.animateCamera(CameraUpdateFactory.newLatLng(lastLatLng), 3000, null);

    //build places query string
    String placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
            "json?location=" + lat + "," + lng +
            "&radius=1000&sensor=true" +
            "&types=food|bar|store|museum|art_gallery" +
            "&key=AIzaSyBUMhJcPA2qfqWL3Rx-klseRLhi7OMP4Lk";//ADD KEY

    //execute query
    new GetPlaces().execute(placesSearchStr);

    locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, (android.location.LocationListener) this);
}

private class GetPlaces extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... placesURL) {
        //fetch places

        //build result as string
        StringBuilder placesBuilder = new StringBuilder();
        //process search parameter string(s)
        for (String placeSearchURL : placesURL) {
            HttpClient placesClient = new DefaultHttpClient();
            try {
                //try to fetch the data

                //HTTP Get receives URL string
                HttpGet placesGet = new HttpGet(placeSearchURL);
                //execute GET with Client - return response
                HttpResponse placesResponse = placesClient.execute(placesGet);
                //check response status
                StatusLine placeSearchStatus = placesResponse.getStatusLine();
                //only carry on if response is OK
                if (placeSearchStatus.getStatusCode() == 200) {
                    //get response entity
                    HttpEntity placesEntity = placesResponse.getEntity();
                    //get input stream setup
                    InputStream placesContent = placesEntity.getContent();
                    //create reader
                    InputStreamReader placesInput = new InputStreamReader(placesContent);
                    //use buffered reader to process
                    BufferedReader placesReader = new BufferedReader(placesInput);
                    //read a line at a time, append to string builder
                    String lineIn;
                    while ((lineIn = placesReader.readLine()) != null) {
                        placesBuilder.append(lineIn);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return placesBuilder.toString();
    }

    //process data retrieved from doInBackground
    protected void onPostExecute(String result) {
        //parse place data returned from Google Places
        //remove existing markers
        if (placeMarkers != null) {
            for (int pm = 0; pm < placeMarkers.length; pm++) {
                if (placeMarkers[pm] != null)
                    placeMarkers[pm].remove();
            }
        }
        try {
            //parse JSON

            //create JSONObject, pass stinrg returned from doInBackground
            JSONObject resultObject = new JSONObject(result);
            //get "results" array
            JSONArray placesArray = resultObject.getJSONArray("results");
            //marker options for each place returned
            places = new MarkerOptions[placesArray.length()];
            //loop through places
            for (int p = 0; p < placesArray.length(); p++) {
                //parse each place
                //if any values are missing we won't show the marker
                boolean missingValue = false;
                LatLng placeLL = null;
                String placeName = "";
                String vicinity = "";
                int currIcon = otherIcon;
                try {
                    //attempt to retrieve place data values
                    missingValue = false;
                    //get place at this index
                    JSONObject placeObject = placesArray.getJSONObject(p);
                    //get location section
                    JSONObject loc = placeObject.getJSONObject("geometry")
                            .getJSONObject("location");
                    //read lat lng
                    placeLL = new LatLng(Double.valueOf(loc.getString("lat")),
                            Double.valueOf(loc.getString("lng")));
                    //get types
                    JSONArray types = placeObject.getJSONArray("types");
                    //loop through types
                    for (int t = 0; t < types.length(); t++) {
                        //what type is it
                        String thisType = types.get(t).toString();
                        //check for particular types - set icons
                        if (thisType.contains("food")) {
                            currIcon = foodIcon;
                            break;
                        } else if (thisType.contains("bar")) {
                            currIcon = drinkIcon;
                            break;
                        } else if (thisType.contains("store")) {
                            currIcon = shopIcon;
                            break;
                        }
                    }
                    //vicinity
                    vicinity = placeObject.getString("vicinity");
                    //name
                    placeName = placeObject.getString("name");
                } catch (JSONException jse) {
                    Log.v("PLACES", "missing value");
                    missingValue = true;
                    jse.printStackTrace();
                }
                //if values missing we don't display
                if (missingValue) places[p] = null;
                else
                    places[p] = new MarkerOptions()
                            .position(placeLL)
                            .title(placeName)
                            .icon(BitmapDescriptorFactory.fromResource(currIcon))
                            .snippet(vicinity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (places != null && placeMarkers != null) {
            for (int p = 0; p < places.length && p < placeMarkers.length; p++) {
                //will be null if a value was missing
                if (places[p] != null)
                    placeMarkers[p] = theMap.addMarker(places[p]);
            }
        }

    }
}

@Override
protected void onResume() {
    super.onResume();
    if (theMap != null) {
        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;
        }
        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;
        }
        locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, (android.location.LocationListener) this);
    }
}

@Override
protected void onPause() {
    super.onPause();
    if (theMap != null) {

        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;
        }
        locMan.removeUpdates((android.location.LocationListener) this);
        }
    }

我不知道如何解决这个问题

0 个答案:

没有答案