Skip to content

What’s Nearby Category

In this guide you will learn how to search for points of interest (POIs) near the current location looking for a certain type of POIs, like gas stations.

Setup

First, get an API key token, see the Getting Started guide.

Download the Maps & Navigation SDK for Android archive file

Download the WhatsNearbyCategory project archive file or clone the project with Git

See the Configure Android Example guide.

Run the example

In Android Studio, from the File menu, select Sync Project with Gradle Files

What's nearby category example Android screenshot

What's nearby category example Android screenshot

What's nearby category example Android screenshot

An android device should be connected via USB cable.
Press SHIFT+F10 to compile, install and run the example on the android device.
A scrollable text list of results is shown of points of interest (POIs) in the gas station category near the current location of the device.

How it works

Android example screenshot

You can open the MainActivity.kt file to see how to search for POIs of a certain category near the current actual or simulated location.

 1private val searchService = SearchService(
 2     onStarted = {
 3         progressBar.visibility = View.VISIBLE
 4     },
 5     onCompleted = onCompleted@{ results, errorCode, _ ->
 6         progressBar.visibility = View.GONE
 7
 8         when (errorCode) {
 9             GemError.NoError -> {
10                 val reference = reference ?: return@onCompleted
11                 if (results.isEmpty()) {
12                     // The search completed without errors, but there were no results found.
13                     showToast("No results!")
14                     return@onCompleted
15                 }
16                 listView.adapter = CustomAdapter(reference, results)
17             }
18
19             GemError.Cancel -> {
20                 // The search action was cancelled.
21             }
22             else -> {
23                 // There was a problem at computing the search operation.
24                 showToast("Search service error: ${GemError.getMessage(errorCode)}")
25             }
26         }
27     }
28)
A searchService = SearchService() is instantiated to carry out searching for POIs around the current actual or simulated position of the device. The onCompleted listener is defined, which is invoked when the search completes, and checks if there was no error, and that the results are not empty, and in that case, passes the non-empty result list to the CustomAdapter to be displayed in a scrollable list of nearby POIs.
 1override fun onCreate(savedInstanceState: Bundle?) {
 2     super.onCreate(savedInstanceState)
 3     setContentView(R.layout.activity_main)
 4
 5     listView = findViewById(R.id.list_view)
 6     progressBar = findViewById(R.id.progressBar)
 7     val layoutManager = LinearLayoutManager(this)
 8     listView.layoutManager = layoutManager
 9
10     val separator = DividerItemDecoration(applicationContext, layoutManager.orientation)
11     listView.addItemDecoration(separator)
12
13     listView.setBackgroundResource(R.color.white)
14     val lateralPadding = resources.getDimension(R.dimen.bigPadding).toInt()
15     listView.setPadding(lateralPadding, 0, lateralPadding, 0)
16
17     SdkSettings.onMapDataReady = onMapDataReady@{ isReady ->
18         if (!isReady) return@onMapDataReady
19
20         // Defines an action that should be done after the world map is ready.
21         search()
22     }
23     SdkSettings.onApiTokenRejected = {
24         showToast("TOKEN REJECTED")
25     }
26     // This step of initialization is mandatory for using the SDK without a map.
27     if (!GemSdk.initSdkWithDefaults(this)) {
28         // The SDK initialization was not completed.
29         finish()
30     }
31     /*
32     The SDK initialization completed successfully, but for the search action
33     to be executed properly, the app needs permission to get the device location.
34     Not requesting this permission or not granting it will make the search fail.
35      */
36     requestPermissions(this)
37
38     if (!Util.isInternetConnected(this)) {
39         Toast.makeText(this, "You must be connected to internet!",
40             Toast.LENGTH_LONG).show()
41     }
42}
MainActivity overrides the onCreate function, which checks that internet access is available, initializes the SDK, and requests location permission from the user. Then, when the map is ready, that is, loaded and initialized, it automatically invokes the search.
The search triggers the onCompleted listener below which passes the resulting list of POIs, if not empty, to a CustomAdapter to be displayed as a scrollable list.
 1override fun onRequestPermissionsResult(
 2     requestCode: Int,
 3     permissions: Array<String>,
 4     grantResults: IntArray
 5 ) {
 6     super.onRequestPermissionsResult(requestCode, permissions, grantResults)
 7     PermissionsHelper.onRequestPermissionsResult(
 8         this,
 9         requestCode,
10         grantResults
11     )
12     val result = grantResults[permissions.indexOf(Manifest.permission.ACCESS_FINE_LOCATION)]
13     if (result != PackageManager.PERMISSION_GRANTED) {
14         finish()
15         exitProcess(0)
16     }
17     postOnMain { search() }
18}
19private fun requestPermissions(activity: Activity): Boolean {
20     val permissions = arrayListOf(
21         Manifest.permission.INTERNET,
22         Manifest.permission.ACCESS_FINE_LOCATION,
23         Manifest.permission.ACCESS_COARSE_LOCATION,
24         Manifest.permission.ACCESS_NETWORK_STATE
25     )
26     return PermissionsHelper.requestPermissions(
27         REQUEST_PERMISSIONS,
28         activity,
29         permissions.toTypedArray()
30     )
31}
Before actually trying a search, it may be necessary to first request location permission for the example app from the user. The onCreate() function requests the permission to access the device location using requestPermissions()
 1private fun search() = SdkCall.execute {
 2     // If one of the location permissions is granted, we can do the search around action.
 3     val hasPermissions =
 4         PermissionsHelper.hasPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
 5     if (!hasPermissions) return@execute
 6
 7     PositionService().getCurrentPosition()?.let {
 8         searchAround(it)
 9     }
10}
11private fun searchAround(reference: Coordinates) = SdkCall.execute {
12     this.reference = reference
13
14     // Cancel any search that is in progress now.
15     searchService.cancelSearch()
16
17     // Search around position using the provided search preferences and/ or filter.
18     searchService.searchAroundPosition(EGenericCategoriesIDs.GasStation)
19}
If location permission was given by the user, then the search() function can call the searchAround() function, which cancels the ongoing search in progress, if any, and then starts a search for gas station POIs:
searchService.searchAroundPosition(EGenericCategoriesIDs.GasStation) and when the search completes, the searchService.onCompleted listener callback function, defined in the searchService, is invoked to put the results in a scrollable list for display, using a CustomAdapter:
 1/**
 2 * This custom adapter is made to facilitate the displaying of the data from the model
 3 * and to decide how it is displayed.
 4 */
 5class CustomAdapter(private val reference: Coordinates, private val dataSet: ArrayList<Landmark>) :
 6    RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
 7    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
 8        val text: TextView = view.findViewById(R.id.text)
 9        val status: TextView = view.findViewById(R.id.status_text)
10        val description: TextView = view.findViewById(R.id.status_description)
11 }
12 override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
13     val view = LayoutInflater.from(viewGroup.context)
14         .inflate(R.layout.list_item, viewGroup, false)
15
16     return ViewHolder(view)
17 }
18 override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) = SdkCall.execute {
19     val meters = dataSet[position].coordinates?.getDistance(reference)?.toInt() ?: 0
20     val dist = getDistText(meters, EUnitSystem.Metric, true)
21
22     viewHolder.text.text = dataSet[position].name
23     viewHolder.status.text = dist.first
24     viewHolder.description.text = dist.second
25 } ?: Unit
26 override fun getItemCount() = dataSet.size
27}

Android Examples

Maps SDK for Android Examples can be downloaded or cloned with Git