使用Mapbox从地址中获取纬度和经度

4

有没有人有使用Mapbox获取地址的纬度和经度的示例?

2个回答

2

查看Mapbox Android SDK指南,按照以下步骤操作:

不要在主UI线程上执行任何示例代码。

示例1:

请注意,position参数是可选的,但会加快获取结果的速度。

// position used for proximity
Position position = Position.fromCoordinates(-73.98572, 40.74843);

MapboxGeocoding client = new MapboxGeocoding.Builder()
            .setAccessToken("<your access token here>")
            .setLocation("Empire State Building")
            .setProximity(position)
            .build();

Response<GeocodingResponse> response = client.execute();

例子2:

MapboxGeocoding client = new MapboxGeocoding.Builder()
            .setAccessToken("<your access token here>")
            .setLocation("Empire State Building")
            .build();

Response<GeocodingResponse> response = client.execute();

这和我想要的相反。我拥有地址,想要它的坐标。但是感谢回复。 - Tiago Taraczuk
1
提供的坐标范围太小,无法缩小地址搜索范围。 - Clive Seebregts
Clive 的说法是正确的,坐标用于偏置结果。这是一个可选参数,但可以加快获取结果的速度。要在 Android 应用程序中使用我们的地理编码器的完整示例,请首先在 build.gradle 中包含 Mapbox Android Services SDK,并按照此示例进行操作。 - cammace
谢谢@cammace - 我会在我的答案中更新你的关于可选参数的评论。 - Clive Seebregts

2
你必须使用 Mapbox.GeocodingBuilder,获取一个 Response,并从 Response 中访问你想要的字段。
这里是我在网上找到并稍作编辑的一个简单示例。
private void simpleSample() {
    MapboxGeocoder client = new MapboxGeocoder.Builder()
            .setAccessToken(MAPBOX_ACCESS_TOKEN)
            .setLocation("The White House")
            .build();

    client.enqueue(new Callback<GeocoderResponse>() {
        @Override
        public void onResponse(Response<GeocoderResponse> response, Retrofit retrofit) {
            // Features, basically, is a list of search results
            // get the first one
            // get latitude and longitude
            String latitude = response.body().getFeatures().get(0).getLatitude();
            String longitude = response.body().getFeatures().get(0).getLongitude();
        }

        @Override
        public void onFailure(Throwable t) {
            // log t.getMessage()
        }
    });
}

您可以在API 101网页上了解有关Mapbox地理编码API的基础知识。
您可以在Mapbox地理编码API文档页面上看到一些官方示例。
您可以在API正向地理编码游乐场页面上尝试搜索术语并查看地图或原始JSON结果,这对于查看结果数据的形状以及如何遍历它非常有用(注意:您必须登录Mapbox帐户才能执行此操作,但如果您没有帐户,则可以免费创建一个)。
(全面披露:我曾为SmartyStreets工作,这是一家地址验证和自动完成公司,其竞争产品。)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接