【问题标题】:Android get near by places and their extended place data (phone, rating, open hours...)Android 通过地点及其扩展地点数据(电话、评级、营业时间...)靠近
【发布时间】:2018-03-17 23:59:45
【问题描述】:

我正在编写一个 Android 应用,用于显示您所在位置附近的披萨店 为此,我使用 URL 调用谷歌地图: https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={latitude,longitude}&type=pizza&sensor=true&key={MY_KEY}

我正在通过扩展 AsyncTask 并使用方法 doInBackground 和 onPostExecute 来处理数据。

从我获取和解析的数据中,我得到了地点 id,现在我想再次调用谷歌来获取地点信息电话,评级,开放......(你不会从附近的地方获得这些数据信息)我看到您可以使用以下方式向谷歌发起 URL 调用: https://maps.googleapis.com/maps/api/place/details/json?key={MY_KEY}&placeid={PLACE_ID}

但我不想在 AsyncTask 中调用 AsyncTask。 基本上我想调用第一个 URL 并在解析每个地方时获取扩展信息。

我该怎么做? 我的代码是:

公共类 MapGetNearbyPlacesData 扩展 AsyncTask {

public final static int MAP_INDEX = 0;
public final static int URL_INDEX = 1;
private String googlePlacesData;
private GoogleMap map;
private String url;

@Override
protected String doInBackground(Object... objects) {
    this.map = (GoogleMap)objects[MAP_INDEX];
    this.url = (String)objects[URL_INDEX];

    try {
        this.googlePlacesData = MapDownloadURL.readUrl(this.url);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return this.googlePlacesData;
}

@Override
protected void onPostExecute(String s) {
    List<HashMap<String, String>> nearbyPlaceList;
    nearbyPlaceList = MapDataParser.parseNearbyPlaces(s);
    showNearbyPlaces(nearbyPlaceList);
}

private void showNearbyPlaces(List<HashMap<String, String>> nearbyPlaceList) {
    for(int i = 0; i < nearbyPlaceList.size(); i++) {
        MarkerOptions markerOptions = new MarkerOptions();
        HashMap<String, String> googlePlace = nearbyPlaceList.get(i);

        String placeName = googlePlace.get(StringUtils.MAP_PALACE_NAME);
        String vicinity = googlePlace.get(StringUtils.MAP_VICINITY);
        double lat = Double.parseDouble(googlePlace.get(StringUtils.MAP_LATITUDE));
        double lng = Double.parseDouble(googlePlace.get(StringUtils.MAP_LONGITUDE));
        String placeId = googlePlace.get(StringUtils.PLACE_ID);

       //how can I get the extended place info here?


        LatLng latLng = new LatLng(lat, lng);
        markerOptions.position(latLng);
        //build all necessary information to display in info window.
        String title = new StringBuilder()
                .append(placeName).append(StringUtils.infoWindowSplitter)
                .append(vicinity).append(StringUtils.infoWindowSplitter)
                .append(placeId).toString();

        markerOptions.title(title);
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
        this.map.addMarker(markerOptions);
    }
}

}

【问题讨论】:

    标签: android google-maps url android-asynctask


    【解决方案1】:

    请参考 Google Places API:

    https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+lat+","+lng+"&radius=10000&type=PlaceType&key=*************************
    

    对于关键阅读文档: https://cloud.google.com/maps-platform/places/

    【讨论】:

      【解决方案2】:

      我可以建议使用 Google Maps API Web Services 的 Java 客户端库来执行 AsyncTask 中的 Places API 请求。

      https://github.com/googlemaps/google-maps-services-java

      使用此库,您可以执行附近搜索、获取地点并循环遍历项目并执行地点详细信息以获取最完整的地点数据。

      您可以通过 Gradle 在项目中添加 Java 客户端库

      dependencies { compile 'com.google.maps:google-maps-services:(insert latest version)' compile 'org.slf4j:slf4j-nop:1.7.25' }

      为了演示它的工作原理,我创建了一个简单的示例。看看 MapGetNearbyPlacesData 类的实现。

      public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
      
          private GoogleMap mMap;
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_maps);
              // Obtain the SupportMapFragment and get notified when the map is ready to be used.
              SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                      .findFragmentById(R.id.map);
              mapFragment.getMapAsync(this);
          }
      
          @Override
          public void onMapReady(GoogleMap googleMap) {
              mMap = googleMap;
      
              mMap.getUiSettings().setZoomControlsEnabled(true);
      
              mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
      
                  @Override
                  public View getInfoWindow(Marker arg0) {
                      return null;
                  }
      
                  @Override
                  public View getInfoContents(Marker marker) {
      
                      Context context = getApplicationContext();
      
                      LinearLayout info = new LinearLayout(context);
                      info.setOrientation(LinearLayout.VERTICAL);
      
                      TextView title = new TextView(context);
                      title.setTextColor(Color.BLACK);
                      title.setGravity(Gravity.CENTER);
                      title.setTypeface(null, Typeface.BOLD);
                      title.setText(marker.getTitle());
      
                      TextView snippet = new TextView(context);
                      snippet.setTextColor(Color.GRAY);
                      snippet.setText(marker.getSnippet());
      
                      info.addView(title);
                      info.addView(snippet);
      
                      return info;
                  }
              });
      
              LatLng center = new LatLng(41.385064,2.173403);
              mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(center, 13.0f));
      
              new MapGetNearbyPlacesData().execute(mMap);
          }
      
          private static class MapGetNearbyPlacesData extends AsyncTask<GoogleMap, Void, List<MarkerOptions>> {
      
              private GoogleMap map;
              private String TAG = "so49343164";
      
              @Override
              protected List<MarkerOptions> doInBackground(GoogleMap... maps) {
                  this.map = maps[0];
      
                  List<MarkerOptions> options = new ArrayList<>();
      
                  GeoApiContext context = new GeoApiContext.Builder()
                          .apiKey("AIza......")
                          .build();
      
                  NearbySearchRequest req = PlacesApi.nearbySearchQuery(context, new com.google.maps.model.LatLng(41.385064,2.173403));
                  try {
                      PlacesSearchResponse resp = req.keyword("pizza").type(PlaceType.RESTAURANT).radius(2000).await();
                      if (resp.results != null && resp.results.length > 0) {
                          for (PlacesSearchResult r : resp.results) {
                              PlaceDetails details = PlacesApi.placeDetails(context,r.placeId).await();
      
                              String name = details.name;
                              String address = details.formattedAddress;
                              URL icon = details.icon;
                              double lat = details.geometry.location.lat;
                              double lng = details.geometry.location.lng;
                              String vicinity = details.vicinity;
                              String placeId = details.placeId;
                              String phoneNum = details.internationalPhoneNumber;
                              String[] openHours = details.openingHours!=null ? details.openingHours.weekdayText : new String[0];
                              String hoursText = "";
                              for(String sv : openHours) {
                                  hoursText += sv + "\n";
                              }
                              float rating = details.rating;
      
                              String content = address + "\n" +
                                      "Place ID: " + placeId + "\n" +
                                      "Rating: " + rating + "\n" +
                                      "Phone: " + phoneNum + "\n" +
                                      "Open Hours: \n" + hoursText;
      
                              options.add(new MarkerOptions().position(new LatLng(lat, lng))
                                      .title(name)
                                      .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeStream(icon.openConnection().getInputStream())))
                                      .snippet(content)
                              );
                          }
                      }
                  } catch(Exception e) {
                      Log.e(TAG, "Error getting places", e);
                  }
                  return options;
              }
      
              @Override
              protected void onPostExecute(List<MarkerOptions> options) {
                  for(MarkerOptions opts : options) {
                      this.map.addMarker(opts);
                  }
              }
      
              @Override
              protected void onPreExecute() {}
      
              @Override
              protected void onProgressUpdate(Void... values) {}
          }
      }
      

      结果是

      您还可以在 GitHub 上找到完整的示例项目:

      https://github.com/xomena-so/so49343164

      不要忘记用您的 API 密钥替换 API 密钥。

      我希望这会有所帮助!

      【讨论】:

      • 我将创建一个新的异步任务来获取详细信息。然后查看你在第一个异步任务 onPpstExucute 函数中的结果。
      猜你喜欢
      • 2011-12-23
      • 1970-01-01
      • 2017-03-10
      • 2012-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      相关资源
      最近更新 更多