android - 如何根据当前位置设置正确的纬度和经度

标签 android geolocation google-places-api

我的目标是使用 Google Places API 进行自动完成预测,现在我想制作某种算法来获取当前位置的纬度和经度,并仅预测 100-200 公里直径范围内的地点。

那么,此时我获取用户当前位置的经纬度,如何设置100-200公里?

 private void getCurrentLocation() {
    mLastLocation = LocationServices.FusedLocationApi
            .getLastLocation(mGoogleApiClient);
    if (mLastLocation != null) {
        double latitude = mLastLocation.getLatitude();
        double longitude = mLastLocation.getLongitude();
        mLatLonBounds = new LatLngBounds(new LatLng(latitude,longitude),
                                  new LatLng(latitude,longitude));
        Log.d("myTag","lat = "+mLatLonBounds.northeast.latitude+" ,lon = "+mLatLonBounds.northeast.longitude);
        //Log.d("myTag","lat = "+mLatLonBounds.southwest.latitude+" ,lon = "+mLatLonBounds.southwest.longitude);

    }else {
        //some code
    }
}

以下是我如何为自动预测设置界限:

  @Nullable
private ArrayList<AutoCompletePlace> getAutocomplete(CharSequence constraint) {
    if (mGoogleApiClient.isConnected()) {
        Log.i(Constants.AUTO_COMPLETE_TAG, "Starting autocomplete query for: " + constraint);

        // Submit the query to the autocomplete API and retrieve a PendingResult that will
        // contain the results when the query completes.
        PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi
                        .getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
                                **mBounds**, mPlaceFilter);

        // This method should have been called off the main UI thread. Block and wait for at most 60s
        // for a result from the API.
        AutocompletePredictionBuffer autocompletePredictions = results.await(60, TimeUnit.SECONDS);

        // Confirm that the query completed successfully, otherwise return null
        final Status status = autocompletePredictions.getStatus();
        if (!status.isSuccess()) {
            Toast.makeText(getContext(), "Error contacting API: " + status.toString(),
                    Toast.LENGTH_SHORT).show();
            Log.e(Constants.AUTO_COMPLETE_TAG, "Error getting autocomplete prediction API call: " + status.toString());
            autocompletePredictions.release();
            return null;
        }

        Log.i(Constants.AUTO_COMPLETE_TAG, "Query completed. Received " + autocompletePredictions.getCount()
                + " predictions.");

        // Copy the results into our own data structure, because we can't hold onto the buffer.
        // AutocompletePrediction objects encapsulate the API response (place ID and description).

        Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator();
        ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount());
        while (iterator.hasNext()) {
            AutocompletePrediction prediction = iterator.next();
            // Get the details of this prediction and copy it into a new PlaceAutocomplete object.
            resultList.add(new AutoCompletePlace(prediction.getPlaceId(),
                    prediction.getDescription()));
        }

        // Release the buffer now that all data has been copied.
        autocompletePredictions.release();

        return resultList;
    }
    Log.e(Constants.AUTO_COMPLETE_TAG, "Google API client is not connected for autocomplete query.");
    return null;

例如我当前的位置 48.6180288,22.2984587。

更新:在 Francois Wouts 给我答案之前,我在 stackoverflow 上找到了另一个解决方案,你也可以使用它。

 public static final LatLngBounds setBounds(Location location, int mDistanceInMeters ){
    double latRadian = Math.toRadians(location.getLatitude());
    double degLatKm = 110.574235;
    double degLongKm = 110.572833 * Math.cos(latRadian);
    double deltaLat = mDistanceInMeters / 1000.0 / degLatKm;
    double deltaLong = mDistanceInMeters / 1000.0 / degLongKm;

    double minLat = location.getLatitude() - deltaLat;
    double minLong = location.getLongitude() - deltaLong;
    double maxLat = location.getLatitude() + deltaLat;
    double maxLong = location.getLongitude() + deltaLong;

    Log.d("Location", "Min: " + Double.toString(minLat) + "," + Double.toString(minLong));
    Log.d("Location","Max: "+Double.toString(maxLat)+","+Double.toString(maxLong));

    // Set up the adapter that will retrieve suggestions from the Places Geo Data API that cover
    // the entire world.

    return new LatLngBounds(new LatLng(minLat,minLong),new LatLng(maxLat,maxLong));

最佳答案

根据 Wikipedia ,您可能希望在用户位置周围的每个方向上允许大约 1 度,以覆盖 100-200 公里。覆盖的确切区域将取决于用户所在的位置,但这对于大多数用例来说应该是一个足够好的近似值。

例如,尝试以下操作:

double radiusDegrees = 1.0;
LatLng center = /* the user's location */;
LatLng northEast = new LatLng(center.latitude + radiusDegrees, center.longitude + radiusDegrees);
LatLng southWest = new LatLng(center.latitude - radiusDegrees, center.longitude - radiusDegrees);
LatLngBounds bounds = LatLngBounds.builder()
        .include(northEast)
        .include(southWest)
        .build();

我相信即使跨过子午线,这也能正常工作。让我知道你过得怎么样!

关于android - 如何根据当前位置设置正确的纬度和经度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32352407/

相关文章:

java - 在没有 youtube 应用程序的情况下将 Youtube 视频集成到应用程序中

textview - Android 自动调整大小的 TextView 的自动换行

javascript - AngularJS,传单。如何从第三方服务动态获取纬度和经度坐标?

ios - CLLocationManager说我在伦敦

android - 在android上不使用 map 对象的附近地点列表

api - Google place Api PlaceDetails图片引用

java - 自定义 Lint 规则未在 eclipse/android studio 中列出

android - 将Android Studio更新到2.1.3版本后,Gradle构建卡住了

python - 如何使用 pandas 和 python 来评估用户位于多少个地理框内?

java - 如何在 gwt 中使用 google app engine