【问题标题】:How to send a Google Places Search Request with Java如何使用 Java 发送 Google Places 搜索请求
【发布时间】:2012-09-09 17:46:50
【问题描述】:

我需要按 long/lat 搜索 Goolge Places Pages 以查找 20m 区域内的任何银行。 这个Google Places Doc 描述了如何使用 JavaScript 来实现。他们正在使用我在 Java 中没有的 google.maps.LatLng 对象。

现在有人如何调用服务吗?

也许还有一个用于 Goolge Places 的 Java API?

最好的问候, 克里斯蒂安。

编辑 1:

我发现someone 构造这样的 url:

String url = baseUrl + "location=" + lat + "," + lon + "&" +
                 "radius=" + searchRadius + "&" + types + "&" + "sensor=true" +
                 "&" + "key=" + googleAPIKey;

答案:编辑 2:

由于上面的帖子,我发现了如何做到这一点。这是一个如何发送请求的示例:

public class GooglePlacesClient
{
    private static final String GOOGLE_API_KEY  = "***";

    private final HttpClient    client          = new DefaultHttpClient();

    public static void main(final String[] args) throws ParseException, IOException, URISyntaxException
    {
        new GooglePlacesClient().performSearch("establishment", 8.6668310, 50.1093060);
    }

    public void performSearch(final String types, final double lon, final double lat) throws ParseException, IOException, URISyntaxException
    {
        final URIBuilder builder = new URIBuilder().setScheme("https").setHost("maps.googleapis.com").setPath("/maps/api/place/search/json");

        builder.addParameter("location", lat + "," + lon);
        builder.addParameter("radius", "5");
        builder.addParameter("types", types);
        builder.addParameter("sensor", "true");
        builder.addParameter("key", GooglePlacesClient.GOOGLE_API_KEY);

        final HttpUriRequest request = new HttpGet(builder.build());

        final HttpResponse execute = this.client.execute(request);

        final String response = EntityUtils.toString(execute.getEntity());

        System.out.println(response);
    }

}

【问题讨论】:

    标签: java google-places-api


    【解决方案1】:

    这里有一个更完整的示例(包括 JSON 解析和一些异常处理),用于 Places API 搜索、自动完成和详细信息。它是为 Android 编写的,但可以很容易地移植到非 Android 使用(需要包含 org.json 库并使用不同的日志记录)。 Place 类是一个简单的值对象。

    package com.example.google.places;
    
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import android.util.Log;
    
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.ArrayList;
    
    /**
     * @author saxman
     */
    public class PlacesService {
        private static final String LOG_TAG = "ExampleApp";
    
        private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
    
        private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
        private static final String TYPE_DETAILS = "/details";
        private static final String TYPE_SEARCH = "/search";
    
        private static final String OUT_JSON = "/json";
    
        // KEY!
        private static final String API_KEY = "YOUR KEY";
    
        public static ArrayList<Place> autocomplete(String input) {
            ArrayList<Place> resultList = null;
    
            HttpURLConnection conn = null;
            StringBuilder jsonResults = new StringBuilder();
            try {
                StringBuilder sb = new StringBuilder(PLACES_API_BASE);
                sb.append(TYPE_AUTOCOMPLETE);
                sb.append(OUT_JSON);
                sb.append("?sensor=false");
                sb.append("&key=" + API_KEY);
                sb.append("&input=" + URLEncoder.encode(input, "utf8"));
    
                URL url = new URL(sb.toString());
                conn = (HttpURLConnection) url.openConnection();
                InputStreamReader in = new InputStreamReader(conn.getInputStream());
    
                int read;
                char[] buff = new char[1024];
                while ((read = in.read(buff)) != -1) {
                    jsonResults.append(buff, 0, read);
                }
            } catch (MalformedURLException e) {
                Log.e(LOG_TAG, "Error processing Places API URL", e);
                return resultList;
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error connecting to Places API", e);
                return resultList;
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
    
            try {
                // Create a JSON object hierarchy from the results
                JSONObject jsonObj = new JSONObject(jsonResults.toString());
                JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
    
                // Extract the Place descriptions from the results
                resultList = new ArrayList<Place>(predsJsonArray.length());
                for (int i = 0; i < predsJsonArray.length(); i++) {
                    Place place = new Place();
                    place.reference = predsJsonArray.getJSONObject(i).getString("reference");
                    place.name = predsJsonArray.getJSONObject(i).getString("description");
                    resultList.add(place);
                }
            } catch (JSONException e) {
                Log.e(LOG_TAG, "Error processing JSON results", e);
            }
    
            return resultList;
        }
    
        public static ArrayList<Place> search(String keyword, double lat, double lng, int radius) {
            ArrayList<Place> resultList = null;
    
            HttpURLConnection conn = null;
            StringBuilder jsonResults = new StringBuilder();
            try {
                StringBuilder sb = new StringBuilder(PLACES_API_BASE);
                sb.append(TYPE_SEARCH);
                sb.append(OUT_JSON);
                sb.append("?sensor=false");
                sb.append("&key=" + API_KEY);
                sb.append("&keyword=" + URLEncoder.encode(keyword, "utf8"));
                sb.append("&location=" + String.valueOf(lat) + "," + String.valueOf(lng));
                sb.append("&radius=" + String.valueOf(radius));
    
                URL url = new URL(sb.toString());
                conn = (HttpURLConnection) url.openConnection();
                InputStreamReader in = new InputStreamReader(conn.getInputStream());
    
                int read;
                char[] buff = new char[1024];
                while ((read = in.read(buff)) != -1) {
                    jsonResults.append(buff, 0, read);
                }
            } catch (MalformedURLException e) {
                Log.e(LOG_TAG, "Error processing Places API URL", e);
                return resultList;
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error connecting to Places API", e);
                return resultList;
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
    
            try {
                // Create a JSON object hierarchy from the results
                JSONObject jsonObj = new JSONObject(jsonResults.toString());
                JSONArray predsJsonArray = jsonObj.getJSONArray("results");
    
                // Extract the Place descriptions from the results
                resultList = new ArrayList<Place>(predsJsonArray.length());
                for (int i = 0; i < predsJsonArray.length(); i++) {
                    Place place = new Place();
                    place.reference = predsJsonArray.getJSONObject(i).getString("reference");
                    place.name = predsJsonArray.getJSONObject(i).getString("name");
                    resultList.add(place);
                }
            } catch (JSONException e) {
                Log.e(LOG_TAG, "Error processing JSON results", e);
            }
    
            return resultList;
        }
    
        public static Place details(String reference) {
            HttpURLConnection conn = null;
            StringBuilder jsonResults = new StringBuilder();
            try {
                StringBuilder sb = new StringBuilder(PLACES_API_BASE);
                sb.append(TYPE_DETAILS);
                sb.append(OUT_JSON);
                sb.append("?sensor=false");
                sb.append("&key=" + API_KEY);
                sb.append("&reference=" + URLEncoder.encode(reference, "utf8"));
    
                URL url = new URL(sb.toString());
                conn = (HttpURLConnection) url.openConnection();
                InputStreamReader in = new InputStreamReader(conn.getInputStream());
    
                // Load the results into a StringBuilder
                int read;
                char[] buff = new char[1024];
                while ((read = in.read(buff)) != -1) {
                    jsonResults.append(buff, 0, read);
                }
            } catch (MalformedURLException e) {
                Log.e(LOG_TAG, "Error processing Places API URL", e);
                return null;
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error connecting to Places API", e);
                return null;
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
    
            Place place = null;
            try {
                // Create a JSON object hierarchy from the results
                JSONObject jsonObj = new JSONObject(jsonResults.toString()).getJSONObject("result");
    
                place = new Place();
                place.icon = jsonObj.getString("icon");
                place.name = jsonObj.getString("name");
                place.formatted_address = jsonObj.getString("formatted_address");
                if (jsonObj.has("formatted_phone_number")) {
                    place.formatted_phone_number = jsonObj.getString("formatted_phone_number");
                }
            } catch (JSONException e) {
                Log.e(LOG_TAG, "Error processing JSON results", e);
            }
    
            return place;
        }
    }
    

    【讨论】:

    • 谢谢你救了我的命 :)
    【解决方案2】:

    GitHub 和 Maven Central 上提供了一个用于使用 Google Places API 的 Java 库(披露:我是开发人员。)获取地点列表(或详细信息、照片等)可以一次性完成或两行。有关示例和设置详细信息,请参见项目页面。

    https://github.com/pushbit/sprockets

    【讨论】:

      【解决方案3】:

      不存在任何可用于 Google Places API 的官方 Java 库。然而,有几个项目托管在 Github 上。另一个是这样的: Google Places API Java Library on Github

      【讨论】:

      • 需要注意的是,链接的仓库是原项目的一个fork。原始仓库位于here
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 2013-08-08
      • 2013-03-25
      • 2018-01-08
      • 2022-01-10
      相关资源
      最近更新 更多