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

2024-04-26

我的目标是使用 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));

根据维基百科 https://en.wikipedia.org/wiki/Decimal_degrees,您可能希望在用户位置周围的每个方向上允许大约 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();

我相信即使跨越前子午线,这也应该能正常工作。让我知道你怎么去!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何根据当前位置设置正确的纬度和经度 的相关文章

随机推荐

  • android 获取设备整体音频输出(PCM)

    有什么方法可以拦截或读取 Android 设备中的音频输出吗 我需要从 myActivity 内部读取 PCM 中的整个音频输出 包括后台的媒体播放器应用程序 通话中的语音 myActivity 内的 MediaPlayer 实例等 以及扬
  • Android SDK 工具 Rev.17 - onClick - 未找到相应的方法处理程序

    我将 Android SDK 工具更新到修订版 17 打开 Eclipse 后 我在 问题 视图中发现了更新之前不存在的新错误列表 这些错误出现在 XML 布局文件中 我在其中定义了按钮的 onClick 属性 鼠标悬停时错误消息示例 未找
  • 将 localStorage 数据设置为只读

    我正在开发 AngularJs 应用程序 我将数据存储在 localStorage 中 localStorageService set selectedUserCategory Circle 现在当我看到浏览器的 localStorage
  • Neo4j.rb 创建独特的关系

    这是我的 Neo4j 活动节点 class User include Neo4j ActiveNode has many out following type following model class User end john User
  • 将图像从 CV_64F 转换为 CV_8U

    我想转换类型的图像CV 64FC1 to CV 8UC1在 Python 中使用 OpenCV 在 C 中 使用convertTo函数 我们可以使用以下代码片段轻松转换图像类型 image convertTo image CV 8UC1 我
  • 如何获取 CakePHP 3.0 中最后一个插入 ID?

    使用 CakePHP 3 0 beta 似乎是一个简单的问题 但我搜索了文档但找不到任何东西 使用 this gt Model gt save 插入新记录后 我想获取新创建记录的 auto increment 主键 ID 使用 Cake 2
  • 使用 ALT+TAB 切换程序/窗口或单击任务栏时不会触发 VisibilityChange 事件

    问题在于事件 visibilitychange 的行为 已触发 当我切换到浏览器窗口内的不同选项卡时 当我单击浏览器窗口的最小化 恢复按钮时 还行吧 它没有被触发 当我使用 ALT TAB 切换到不同的窗口 程序时 当我切换到不同的窗口 程
  • 有没有办法将 spring boot 与 tcps 连接到数据库?

    我正在使用 Oracle 数据库 12c 和带有数据 JPA 的 Spring Boot 2 3 我的目标是连接钱包并将 TCPS 发送到数据库 当我搜索时 网上没有这方面的示例或指南 任何人都可以解释并举一些例子吗 如何从 Java 连接
  • Laravel 5 - 永远保持登录状态

    我想放入login页面选中 保持登录状态 复选框 除非用户注销 否则永远不应该结束用户的会话 我知道在 app config session php 中有这些变量 lifetime gt 60 expire on close gt fals
  • 从 boto3 调用 AWS Glue Pythonshell 作业时出现参数错误

    基于上一篇文章 https stackoverflow com questions 58044032 retrieving s3 path from payload inside aws glue pythonshell job 58044
  • NodeJS 连接到 SQL Server getaddrinfo ENOTFOUNT

    我正在尝试使用 Knex js 连接到 Microsoft SQL Server 但收到 getaddrinfo ENOTFOUND 我知道这表明 NodeJS 无法解析地址 通常是通过 DNS 或协议问题 const knex requi
  • 离线世界卫星地图无标签(Android)

    我想在我的应用程序中包含 MapView 我已经尝试了一下 Google Api 它运行得很好 但现在我想要一张完全离线的地图 我知道有很多可能性可以做到这一点 问题是我想要一张没有任何标签的世界地图 例如国家名称 州名称 城市名称等 我只
  • 如何在我的 django 视图函数中从 Ajax POST 获取数据?

    document ready function addFolder input keydown function e if e keyCode 13 name this val ajax type POST url folder data
  • ie7 中的 JQuery Event.target 问题

    尝试从 event target 对象访问类名 适用于 FF Safari 和 Chrome InternetExplorer 7 警告 未定义 有什么建议么
  • Apache Poi:获取 DOC 文档中的页数

    如何使用 Apache Poi 获取 DOC 文档中的页数 我尝试使用以下代码 HWPFDocument wordDoc new HWPFDocument new FileInputStream lowerFilePath Integer
  • 我如何获得 NSDictionary/NSMutableDictionary 的原始顺序?

    我已经创建了带有 10 个键的 NSMutableDictionary 现在我想按照添加到 NSMutableDictionary 的顺序访问 NSMutableDictionary 键 使用 SetValue forKey 我怎样才能做到
  • 下载使用 MVC5 选择的多个文件

    我正在 MVC5 中开发一个视图 如下所示 我需要选择表中的一条或多条记录 并能够下载数据库中以前保存的文件 我一直在寻找解决方案并做了多次测试 但我找不到解决方案 我试图从 javascript 将选定的代码发送到控制器并从中下载文档 但
  • 在我的 angular-cli 项目中从 node-sass 切换到 dart sass

    我在 npm install 期间遇到了 node sass 做各种愚蠢的问题 包括但不限于 GNU c 编译一些东西 可能是它本身 尝试运行python2 7 尝试运行任何其他版本的 python 尝试连接到github 这在企业环境中造
  • XSD 属性 NILLABLE 不起作用

    我正在努力获取一个 xml 文件来根据 XSD 架构进行验证 但我在验证时遇到了问题 每次我验证时都会收到错误消息 架构有效性错误 元素 http services website com ProgramResponse Populatio
  • 如何根据当前位置设置正确的纬度和经度

    我的目标是使用 Google Places API 进行自动完成预测 现在我想制作某种算法 该算法将采用当前位置的纬度和经度 并仅对直径为 100 200 公里的地点进行预测 那么 此时我获取用户当前位置的纬度和经度 如何设置100 200