简体   繁体   English

使用 Android 中的 Google Maps API 从用户位置获取附近地点的结果

[英]Getting results of nearby places from User's Location using Google Maps API in Android

This is the first time using google map API and google places API.这是第一次使用谷歌地图 API 和谷歌地点 API。 I am doing a demo application that displays the list hospitals (for example) nearest to the user's location with routes to each of the hospitals.我正在做一个演示应用程序,显示最接近用户位置的列表医院(例如)以及到每家医院的路线。 I been able to get the user's location with the code below the:我能够使用以下代码获取用户的位置:

public class MainActivity extends ActionBarActivity {
    private GoogleMap map;
    UiSettings mapSettings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

        if (map != null) {
           // map.addMarker(new MarkerOptions().position(myLocation).title("Start"));
            map.setMyLocationEnabled(true);
            mapSettings = map.getUiSettings();
            mapSettings.setScrollGesturesEnabled(true);
            mapSettings.setZoomControlsEnabled(true);
        }
    }
}

The xml file: xml文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment" />


</RelativeLayout>

My question how do I get the list of hospitals using google places API and display them.我的问题是如何使用谷歌地点 API 获取医院列表并显示它们。 Any help,tips,walkthrough or tutorials will really be appericaited.Thanks in Advance.任何帮助、提示、演练或教程都将真正得到认可。提前致谢。

For Android, I tried to use Place picker for Android .对于 Android,我尝试使用Place picker for Android It can add the built-in place picker UI widget to your app, so users can choose from a set of nearby places displayed on a map.它可以将built-in place picker UI widget到您的应用程序,以便用户可以从地图上显示的一组附近地点中进行选择。 It easy to use, you just need to do is:它易于使用,您只需要做的是:

int PLACE_PICKER_REQUEST = 1;
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();    
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);

It will show the UI below to pick a place for you, and you can get the place info by using below:它将显示下面的用户界面为您选择一个地点,您可以使用以下方法获取地点信息:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == PLACE_PICKER_REQUEST) {
    if (resultCode == RESULT_OK) {
        Place place = PlacePicker.getPlace(data, this);
        String toastMsg = String.format("Place: %s", place.getName());
        Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
    }
  }
}

在此处输入图片说明

For more details, please refer to guide here and code here .有关更多详细信息,请参阅此处的指南和此处的代码。

However, it cannot set the place type because it no feature for the Build in UI.. If you really need to set, you should use Google Places API Web Service API here , search the location yourself, parse the JSON data, and show on your own UI.但是,它不能设置地点类型,因为它没有 UI 构建的功能。如果你真的需要设置,你应该在这里使用Google Places API Web Service API ,自己搜索位置,解析 JSON 数据,然后显示你自己的用户界面。

A Nearby Search lets you search for places within a specified area.附近搜索可让您搜索指定区域内的地点。 You can refine your search request by supplying keywords or specifying the type of place you are searching for.您可以通过提供关键字或指定要搜索的地点类型来优化搜索请求。

A Nearby Search request is an HTTP URL of the following form: Nearby Search 请求是以下形式的 HTTP URL:

https://maps.googleapis.com/maps/api/place/nearbysearch/output?parameters

Note that in parameters you need to set types=hospital注意在参数中需要设置types=hospital

EDIT编辑

Example on how to pass the search request for specific locations in JSON using the google places API web API web service API.关于如何使用谷歌场所 API Web API Web 服务 API 以 JSON 格式传递特定位置的搜索请求的示例。

Request要求

location: -33.8670,151.1957
radius: 500
types: food
name: cruise
key: API_KEY

Url for this:网址:

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670,151.1957&radius=500&types=food&name=cruise&key=API_KEY https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670,151.1957&radius=500&types=food&name=cruise&key=API_KEY

and Response JSON like this:和这样的响应JSON:

{
   "debug_log" : {
      "line" : []
   },
   "html_attributions" : [],
   "logging_info" : {
      "experiment_id" : [],
      "query_geographic_location" : "AU"
   },
   "results" : [
      {
         "geometry" : {
            "location" : {
               "lat" : -33.86879,
               "lng" : 151.194217
            }
         },
         "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
         "id" : "21a0b251c9b8392186142c798263e289fe45b4aa",
         "name" : "Rhythmboat Cruises",
         "opening_hours" : {
            "open_now" : false,
            "weekday_text" : []
         },
         "photos" : [
            {
               "height" : 426,
               "html_attributions" : [
                  "\u003ca href=\"https://www.google.com/maps/views/profile/104066891898402903288\"\u003eRhythmboat Cruises\u003c/a\u003e"
               ],
               "photo_reference" : "CmRdAAAA-YL_I_Gk02blOX6S0nKHry8PFu9pDyp3Y9AnqISsa3Eq8mkbdD5mXuu1Fax60s0nSy3iiX-h5j-ztyLHcc1-782MsLQsgLLa4t3ZgDmCMll-a8ABapZGnZwDKByk67LFEhBgedv_u_eYFsEo9ay8jxJjGhTUHKPJ4G82vBJqSNliuv7UlAtclw",
               "width" : 640
            }
         ],
         "place_id" : "ChIJyWEHuEmuEmsRm9hTkapTCrk",
         "reference" : "CnRmAAAAvQlMKw-XtxEY4vWFCvudF7CEMQGI5ycNbfVgGl9rAF75fdiPOiLJw1k9NL2v8ZIJsOJuRS3Lm9Dw1vga4ajycAs7PlxN1MVnnYT9la0pBvEvSQNlyvszKANS1R4P7Mvk_jhqswMggqCUtwJ13LN2hRIQOiAkLTWUi3DOjVVOw7J5IRoUb_cJyJaJNqKdmkDM2f0OjQjh9F0",
         "scope" : "GOOGLE",
         "types" : [ "restaurant", "food", "point_of_interest", "establishment" ],
         "vicinity" : "Pyrmont Bay Wharf (Near Australia Maritime Museum), Pyrmont, NSW 2009"
      },
      {
         "geometry" : {
            "location" : {
               "lat" : -33.867591,
               "lng" : 151.201196
            }
         },
         "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
         "id" : "a97f9fb468bcd26b68a23072a55af82d4b325e0d",
         "name" : "Australian Cruise Group",
         "opening_hours" : {
            "open_now" : false,
            "weekday_text" : []
         },
         "photos" : [
            {
               "height" : 1331,
               "html_attributions" : [
                  "\u003ca href=\"https://www.google.com/maps/views/profile/110751364053842618118\"\u003eAustralian Cruise Group\u003c/a\u003e"
               ],
               "photo_reference" : "CmRdAAAAtEoj29FJcNBccrsu6bHt0xgwVGhYlciCY1fe6gTr_d5_KkeP3LITnOwnpNRJWnX39B04-aIBOKXKJH6ltx948T5vWIYBoah1yZDXsWngWZ5kMsK7xyCB5P_q_xBIBxxUEhAYWeB4PiOm_Jy093fB-j0iGhSYmIs9xB2aa6u-RH8V8lZEk-Q5ig",
               "width" : 2000
            }
         ],
         "place_id" : "ChIJrTLr-GyuEmsRBfy61i59si0",
         "reference" : "CnRqAAAAFbukrZvRNsc05TreHUCrPEya5NcN9v0fFLLaK-D1fSyxFTuQlUDhDstU3qwXKw_fADX4W6guUkexax1nufgiYIuGCKoZPEnup1r-LhGGNz9dn1uf9Of5iOtZ1XgCeDjJaYvGbSB3C0pAXL8r9kOsmhIQbx2Sia2DAWTjtSZwuh5aehoUhM6upqBCDLhGruZAGGsCOwAiIq8",
         "scope" : "GOOGLE",
         "types" : [
            "restaurant",
            "travel_agency",
            "food",
            "point_of_interest",
            "establishment"
         ],
         "vicinity" : "32 The Promenade, King Street Wharf 5, Sydney"
      },
      {
         "geometry" : {
            "location" : {
               "lat" : -33.870943,
               "lng" : 151.190311
            }
         },
         "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/bar-71.png",
         "id" : "e644f7f34cf875b9919c6548f1b721947362850a",
         "name" : "Lunch Cruise with Jazz on Sydney Harbour",
         "opening_hours" : {
            "open_now" : false,
            "weekday_text" : []
         },
         "photos" : [
            {
               "height" : 292,
               "html_attributions" : [
                  "\u003ca href=\"https://www.google.com/maps/views/profile/105423912060796272053\"\u003eFrom a Google User\u003c/a\u003e"
               ],
               "photo_reference" : "CmRdAAAAR4bqFTKYWdBwZwdBdON_JRD7V_joTwwIPwRUpZIZWkSSd8GQ3P2O-_aQbUJdL2RhoAyzCUIF0f--DI4oXFneTpj5zZfFq-iFiT7i_x0tjnDveIY8tJv-6o0uWSSjYqabEhCKqQWZqrKAoddjDcc64N48GhQZ2T1_ntPzNKCooHpZzlYQ7AxFOA",
               "width" : 438
            }
         ],
         "place_id" : "ChIJLfySpTOuEmsRPCRKrzl8ZEY",
         "reference" : "CoQBewAAAFd2fO_YWGTiT4RzXWb5tsOuOt7YyV_ScQOwm0tqJSrAyACCczeOzV-P_mgZLro1oKP_34Nt0nVC_1OEKAQUcd7cUm7xmAMSX-EkbSWiD0kOWGgGgKuDRtb0t_8qsxBGU_izugWCyK7SRWezTxELYNdkS0OEiSWPnvhxvXuQktBBEhAAtEe7fagW2kUR14T1QpVsGhQBO7YpIyYSPvo4zUJuL_bX30nJZw",
         "scope" : "GOOGLE",
         "types" : [ "bar", "restaurant", "food", "point_of_interest", "establishment" ],
         "vicinity" : "37 Bank St, Pyrmont"
      }
   ],
   "status" : "OK"
}

The below example returns a list of hospitals near London, England.以下示例返回英国伦敦附近的医院列表。

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=51.503186,-0.126446&radius=5000&types=hospital&key=API_KEY

For more details please refer here .有关详细信息,请参阅此处

Follow this link, it has all explained out,按照这个链接,它已经全部解释了,

in the String type='grocery_or_supermarket' replace it to be 'hospital' and you'll be good to go:在 String type='grocery_or_supermarket' 中将其替换为 'hospital' 就可以了:

http://androidmastermind.blogspot.co.ke/2016/06/android-google-maps-with-nearyby-places.html http://androidmastermind.blogspot.co.ke/2016/06/android-google-maps-with-nearyby-places.html

 private void loadNearByPlaces(double latitude, double longitude)

//YOU Can change this type at your own will, e.g hospital, cafe, restaurant.... and see how it all works
{


    mMap.clear();
    Intent i = getIntent();
    String type = hospital;

    StringBuilder googlePlacesUrl =
            new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
    googlePlacesUrl.append("location=").append(latitude).append(",").append(longitude);
    googlePlacesUrl.append("&radius=").append(PROXIMITY_RADIUS);
    googlePlacesUrl.append("&types=").append(type);
    googlePlacesUrl.append("&sensor=true");
    googlePlacesUrl.append("&key=" + GOOGLE_BROWSER_API_KEY);

    JsonObjectRequest request = new JsonObjectRequest(googlePlacesUrl.toString(),
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject result) {

                    Log.i(TAG, "onResponse: Result= " + result.toString());
                    parseLocationResult(result);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(TAG, "onErrorResponse: Error= " + error);
                    Log.e(TAG, "onErrorResponse: Error= " + error.getMessage());
                }
            });

    AppController.getInstance().addToRequestQueue(request);
}

This will load the near by hospital according to your location.这将根据您的位置加载附近的医院。

Follow below code:按照下面的代码:

private static final String TAG_RESULT = "predictions";
JSONObject json;


ArrayList<String> names;
ArrayAdapter<String> adapter;
String browserKey = "Google API key";
//------------------------AutoComplete code--------------  
  public void updateList(String place) {
        String input = "";

        try {
            input = "input=" + URLEncoder.encode(place, "utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        String output = "json";
        String parameter = input + "&types=geocode&sensor=true&key="                + browserKey;

        url = "https://maps.googleapis.com/maps/api/place/autocomplete/"                + output + "?" + parameter;

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, url,
                null, new Response.Listener<JSONObject>() {

            @Override            public void onResponse(JSONObject response) {
                System.out.println("response"+response);
                try {

                    JSONArray ja = response.getJSONArray(TAG_RESULT);

                    for (int i = 0; i < ja.length(); i++) {
                        JSONObject c = ja.getJSONObject(i);
                        String description = c.getString("description");
                        System.out.println("description"+description);
                        names.add(description);
                    }

                    adapter = new ArrayAdapter<String>(
                            getApplicationContext(),
                            android.R.layout.simple_list_item_1, names) {
                        @Override                        public View getView(int position,
                                            View convertView, ViewGroup parent) {
                            View view = super.getView(position,
                                    convertView, parent);
                            TextView text = (TextView) view
                                    .findViewById(android.R.id.text1);
                            text.setTextColor(Color.BLACK);
                            return view;
                        }
                    };
                    edittext_signup_city.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                } catch (Exception e) {
                }
            }
        }, new Response.ErrorListener() {
            @Override            public void onErrorResponse(VolleyError error) {
            }
        });
        AppController.getInstance().addToRequestQueue(jsonObjReq, "jreq");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Android中的Google Maps API显示当前位置和附近地点以及两个地点之间的路线 - Show Current Location and Nearby Places and Route between two places using Google Maps API in Android Android 谷歌地图:哪个 API 用于搜索您当前位置附近的地方? - Android Google Maps: which API used to search places nearby your current location? 在Android上使用Google Places API获取附近地点的列表 - get list of nearby places using google places API on android Android:使用Google Places API查找附近的地点 - Android: Finding nearby places with Google Places API 附近的Google Maps API地方的PlaceFilter - PlaceFilter for nearby google maps api places 使用Google Places API查找附近的地方 - find nearby places using Google Places api Android应用程序-使用Android版Google Places API从特定位置获取兴趣点 - Android Application - Getting points of interest from a certain location using Google Places API for Android 如何使用 Google Place API 创建附近的地方 android 应用程序? - How to create an nearby places android app using Google Place API? Android无法使用Google API检索附近的地方 - Android unable to retrieve nearby places using google api Android:如何使用Google Places API(自动填充)搜索附近的酒店? - Android: How to search for nearby hotels using the Google Places API (Autocomplete)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM