AndroidStudio中如何查找附近的地点并将它们作为标记显示出来?
创始人
2024-08-21 02:30:07
0

步骤1:添加Google Maps API

在Android Studio中的build.gradle(module)文件中添加Google Maps API依赖项:

dependencies {
  implementation 'com.google.android.gms:play-services-maps:17.0.0'
}

步骤2:获取用户位置权限

在AndroidManifest.xml文件中添加以下代码以获取用户位置权限:


步骤3:创建GoogleMap对象

在activity中创建GoogleMap对象:

GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
            .getMapAsync(this);
}

步骤4:获取附近的地点

使用Google Places API获取附近的地点:

private void getNearbyPlaces(LatLng latLng) {

    String type = "restaurant"; //查找餐馆
    double radius = 1000; //1000米以内

    String url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" +
            latLng.latitude + "," + latLng.longitude +
            "&radius=" + radius +
            "&type=" + type +
            "&key=" + API_KEY;

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
            response -> {
                try {
                    JSONArray jsonArray = response.getJSONArray("results");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        JSONObject location = jsonObject.getJSONObject("geometry").getJSONObject("location");
                        double lat = location.getDouble("lat");
                        double lng = location.getDouble("lng");
                        String name = jsonObject.getString("name");
                        MarkerOptions markerOptions = new MarkerOptions();
                        markerOptions.position(new LatLng(lat, lng));
                        markerOptions.title(name);
                        mMap.addMarker(markerOptions);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }, error -> {
                Log.e(TAG,

相关内容

热门资讯

受玩家影响!wepoker透视... 受玩家影响!wepoker透视脚本苹果版(透视)切实存在有辅助app(有挂教程)-哔哩哔哩1、wep...
据公告内容!sohoo竞技联盟... 据公告内容!sohoo竞技联盟辅助器(透视)好像是真的辅助神器(有挂分享)-哔哩哔哩sohoo竞技联...
透视模拟器!hhpoker透视... 透视模拟器!hhpoker透视方法(透视)一贯真的是有辅助工具(有挂规律)-哔哩哔哩1、hhpoke...
透视模拟器!大菠萝免费辅助器(... 透视模拟器!大菠萝免费辅助器(透视)都是真的有辅助神器(有挂猫腻)-哔哩哔哩1、每一步都需要思考,不...
此事引发网友热议!大菠萝免费辅... 此事引发网友热议!大菠萝免费辅助器(透视)真是是有辅助工具(有挂方法)-哔哩哔哩1、打开软件启动之后...
透视好友!wepoker辅助是... 透视好友!wepoker辅助是真的吗(透视)都是存在有辅助神器(有挂秘籍)-哔哩哔哩1、任何wepo...
连日来!wepoker免费透视... 连日来!wepoker免费透视(透视)好像是真的辅助插件(有挂秘籍)-哔哩哔哩1、点击下载安装,we...
据了解!wepoker透视脚本... 据了解!wepoker透视脚本免费使用视频(透视)一贯真的是有辅助软件(有挂分析)-哔哩哔哩;1、让...
透视实锤!hhpoker德州透... 透视实锤!hhpoker德州透视挂(透视)都是真的有辅助神器(有挂教程)-哔哩哔哩1、hhpoker...
刚刚!wpk有辅助器吗(透视)... 刚刚!wpk有辅助器吗(透视)好像有辅助工具(有挂功能)-哔哩哔哩;1、进入到wpk有辅助器吗是否有...