Android:使用Maps API搜索附近的特定地点类型

里沙卜

我正在创建一个Google Maps应用程序。在我的应用程序中,我正在使用“位置”类型“ atm”搜索附近的ATM。一切正常,但是我必须找到附近的特定ATM,例如Axis bank ATM,所以请使用以下代码来解决我的问题....。

public class MainActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private GoogleMap mMap;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    LocationRequest mLocationRequest;
    String[] mPlaceType=null;
    String[] mPlaceTypeName=null;
    Spinner mSprPlaceType;
    double mLatitude=0;
    double mLongitude=0;

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

        // Array of place types
        mPlaceType = getResources().getStringArray(R.array.place_type);

        // Array of place type names
        mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);

        // Creating an array adapter with an array of Place types
        // to populate the spinner
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);

        // Getting reference to the Spinner
        mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);

        // Setting adapter on Spinner to set place types
        mSprPlaceType.setAdapter(adapter);

        Button btnFind;

        // Getting reference to Find Button
        btnFind = (Button) findViewById(R.id.btn_find);

        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

        if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        } else { // Google Play Services are available


            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                checkLocationPermission();
            }
            // 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);
        }

        // Setting click event lister for the find button
        btnFind.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                int selectedPosition = mSprPlaceType.getSelectedItemPosition();
                //String type = mPlaceType[selectedPosition];
                String type = "atm";
                StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
                sb.append("location="+mLatitude+","+mLongitude);
                sb.append("&radius=5000");
                sb.append("&types="+type);
                sb.append("&sensor=true");
                sb.append("&key=******************************");

                // Creating a new non-ui thread task to download json data
                PlacesTask placesTask = new PlacesTask();

                // Invokes the "doInBackground()" method of the class PlaceTask
                placesTask.execute(sb.toString());

            }
        });
    }

    /** A method to download json data from url */
    private String downloadUrl(String strUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb  = new StringBuffer();

            String line = "";
            while( ( line = br.readLine())  != null){
                sb.append(line);
            }

            data = sb.toString();

            br.close();

        }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
        }finally{
            iStream.close();
            urlConnection.disconnect();
        }

        return data;
    }



    /** A class, to download Google Places */
    private class PlacesTask extends AsyncTask<String, Integer, String>{

        String data = null;

        // Invoked by execute() method of this object
        @Override
        protected String doInBackground(String... url) {
            try{
                data = downloadUrl(url[0]);
            }catch(Exception e){
                Log.d("Background Task",e.toString());
            }
            return data;
        }

        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(String result){
            ParserTask parserTask = new ParserTask();

            // Start parsing the Google places in JSON format
            // Invokes the "doInBackground()" method of the class ParseTask
            parserTask.execute(result);
        }
    }

    /** A class to parse the Google Places in JSON format */
    private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{



        // Invoked by execute() method of this object
        @Override
        protected List<HashMap<String,String>> doInBackground(String... jsonData) {

            JSONObject jObject;

            List<HashMap<String, String>> places = new ArrayList<>();
            PlaceJSONParser placeJsonParser = new PlaceJSONParser();

            try{
                jObject = new JSONObject(jsonData[0]);

                /** Getting the parsed data as a List construct */
                places = placeJsonParser.parse(jObject);

            }catch(Exception e){
                Log.d("Exception",e.toString());
            }
            return places;
        }

        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(List<HashMap<String,String>> list){

            // Clears all the existing markers
            mMap.clear();

            for(int i=0;i < list.size();i++){

                // Creating a marker
                MarkerOptions markerOptions = new MarkerOptions();

                // Getting a place from the places list
                HashMap<String, String> hmPlace = list.get(i);

                // Getting latitude of the place
                double lat = Double.parseDouble(hmPlace.get("lat"));

                // Getting longitude of the place
                double lng = Double.parseDouble(hmPlace.get("lng"));

                // Getting name
                String name = hmPlace.get("place_name");

                // Getting vicinity
                String vicinity = hmPlace.get("vicinity");

                if(name.contains("axis")){

                }

                LatLng latLng = new LatLng(lat, lng);

                // Setting the position for the marker
                markerOptions.position(latLng);

                // Setting the title for the marker.
                //This will be displayed on taping the marker
                markerOptions.title(name + " : " + vicinity);

                // Placing a marker on the touched position
                Marker m = mMap.addMarker(markerOptions);

            }
        }
    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    public boolean checkLocationPermission() {
        if(ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED){

            if(ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)){

                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }else {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        }else{
            return true;
        }

    }


    @Override
    public void onConnected(Bundle bundle) {

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest,this);
        }

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onLocationChanged(Location location) {
        mLatitude = location.getLatitude();
        mLongitude = location.getLongitude();
        LatLng latLng = new LatLng(mLatitude, mLongitude);

        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(12));

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;


        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    ==PackageManager.PERMISSION_GRANTED){
                buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);

            }
        }
        else {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }

    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResult){
        switch (requestCode){
            case MY_PERMISSIONS_REQUEST_LOCATION: {

                if(grantResult.length > 0
                        && grantResult[0] == PackageManager.PERMISSION_GRANTED){
                    if(ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {
                        if(mGoogleApiClient == null){
                            buildGoogleApiClient();
                        }
                        mMap.setMyLocationEnabled(true);
                    }

                }else {
                    Toast.makeText(this, "permisison denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

        }
    }
}
7极客

我认为您应该可以通过将返回的地点的名称与所需的文本(在本例中为轴)进行比较来做到这一点。我的意思是,当您执行上述查询时,将返回场所的名称;(此处为所有银行ATM的名称)。您可以做的是检查返回的名称是否包含单词axis。下面的代码可能是一个很好的起点。

protected void onPostExecute(List<HashMap<String, String>> list) {
        if (list.size()>0){
            for (int i = 0; i < list.size(); i++) {
                HashMap<String, String> hmPlace = list.get(i);
                final String name = hmPlace.get("place_name");
                String vicinity = hmPlace.get("vicinity");
                if (name.contains("axis")){
                   //do some awesome stuff here
                   LatLng latLng = new LatLng(lat, lng);

                   // Setting the position for the marker
                   markerOptions.position(latLng);

                  // Setting the title for the marker.
                 //This will be displayed on taping the marker
                 markerOptions.title(name + " : " + vicinity);

                // Placing a marker on the touched position
                Marker m = mMap.addMarker(markerOptions);
                }
            }
        }
    }// onPostExecute
}// end of the parserTask class

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Google Maps API中的附近地点

来自分类Dev

使用Google Places API在Google Maps中查找附近的地点

来自分类Dev

如何使用 Laravel API 显示附近的地点

来自分类Dev

我使用Google Place Api,但在附近的搜索地点(如银行和餐厅&..)使用时,这不起作用?

来自分类Dev

我使用Google Place Api,但是在附近的搜索地点(如银行和餐厅&..)使用时,这不起作用?

来自分类Dev

附近搜索| Google Maps API

来自分类Dev

在 android 上使用谷歌地点 API 获取附近地点的列表

来自分类Dev

如何使用Google API在附近的地点获取20多个结果

来自分类Dev

如何使用 PHP JSON 对象从 Google Maps API 获取 5 个附近地点的纬度和经度?

来自分类Dev

使用Place API在Xamarin android中填充附近地点的地图

来自分类Dev

为什么我不能将Google Maps getCurrentPosition与地点搜索API结合使用

来自分类Dev

google maps api自动完成特定城市的输出地点

来自分类Dev

如何使用uitextfield在Google Maps SDK中搜索地点

来自分类Dev

如何根据特定类别搜索附近的Facebook页面/地点?

来自分类Dev

Google Maps API-地理编码和附近搜索

来自分类Dev

Google Maps API-地理编码和附近搜索

来自分类Dev

在多种类型的近邻搜索中使用Google Maps API

来自分类Dev

从谷歌地点 Web API 获取图片 URL(附近搜索)

来自分类Dev

如何在Google Maps API搜索结果中显示自定义地点?

来自分类Dev

使用Google Maps API连接给定的地点

来自分类Dev

使用带有UWP的Google Places API将数据绑定到ListView以显示到附近地点的距离

来自分类Dev

在Android Studio中使用Gradle管理Google Maps API密钥

来自分类Dev

使用Android版Google Maps API实时动态跟踪路线

来自分类Dev

使用Maps API2 Android的空指针异常?

来自分类Dev

在Google Maps Android API中使用Google Maps离线地图(缓存)

来自分类Dev

在Google Maps Android API中使用Google Maps离线地图(缓存)

来自分类Dev

如何使用带有Google Maps Android API的过滤器搜索餐厅?

来自分类Dev

如何知道Android设备是否在地址附近Google Maps API

来自分类Dev

如何知道Android设备是否在地址附近Google Maps API

Related 相关文章

  1. 1

    Google Maps API中的附近地点

  2. 2

    使用Google Places API在Google Maps中查找附近的地点

  3. 3

    如何使用 Laravel API 显示附近的地点

  4. 4

    我使用Google Place Api,但在附近的搜索地点(如银行和餐厅&..)使用时,这不起作用?

  5. 5

    我使用Google Place Api,但是在附近的搜索地点(如银行和餐厅&..)使用时,这不起作用?

  6. 6

    附近搜索| Google Maps API

  7. 7

    在 android 上使用谷歌地点 API 获取附近地点的列表

  8. 8

    如何使用Google API在附近的地点获取20多个结果

  9. 9

    如何使用 PHP JSON 对象从 Google Maps API 获取 5 个附近地点的纬度和经度?

  10. 10

    使用Place API在Xamarin android中填充附近地点的地图

  11. 11

    为什么我不能将Google Maps getCurrentPosition与地点搜索API结合使用

  12. 12

    google maps api自动完成特定城市的输出地点

  13. 13

    如何使用uitextfield在Google Maps SDK中搜索地点

  14. 14

    如何根据特定类别搜索附近的Facebook页面/地点?

  15. 15

    Google Maps API-地理编码和附近搜索

  16. 16

    Google Maps API-地理编码和附近搜索

  17. 17

    在多种类型的近邻搜索中使用Google Maps API

  18. 18

    从谷歌地点 Web API 获取图片 URL(附近搜索)

  19. 19

    如何在Google Maps API搜索结果中显示自定义地点?

  20. 20

    使用Google Maps API连接给定的地点

  21. 21

    使用带有UWP的Google Places API将数据绑定到ListView以显示到附近地点的距离

  22. 22

    在Android Studio中使用Gradle管理Google Maps API密钥

  23. 23

    使用Android版Google Maps API实时动态跟踪路线

  24. 24

    使用Maps API2 Android的空指针异常?

  25. 25

    在Google Maps Android API中使用Google Maps离线地图(缓存)

  26. 26

    在Google Maps Android API中使用Google Maps离线地图(缓存)

  27. 27

    如何使用带有Google Maps Android API的过滤器搜索餐厅?

  28. 28

    如何知道Android设备是否在地址附近Google Maps API

  29. 29

    如何知道Android设备是否在地址附近Google Maps API

热门标签

归档