androidosmdroidgeocoder

how to search location name on osmdroid to get latitude longitude


how to get the latitude and longitude by search location names with open street map osmdroid.

My Expectation is, It looks like implement google map places autocomplete, but I don't know how to make autocomplete places in osmdroid. I am not found any tutorial for search locations by location name with osmdroid


Solution

  • so I found this way to search location with osmdroid, but it's not what I expected. I am using geocoder to search the location here the reference

    https://developer.android.com/reference/android/location/Geocoder

    In the first step we need to make a search box Edittext to search the location and make the logic looks like this.

    etSearch.setOnEditorActionListener { _, actionId, _ ->
      if (actionId == EditorInfo.IME_ACTION_SEARCH) {
        etSearch.clearFocus()
        val query = etSearch.text.toString()
        if (query != "") {
          getLocationName(query)
          } else {
            Toast.makeText(
              requireContext(),
              getString(R.string.mohon_isi_terlebih_dahulu),
              Toast.LENGTH_SHORT
              ).show()
          }
        }
      true
    }
    

    after getting the query text from the search box we need to call function getLocationName(String) and the function looks like this

    fun getLocationName(locationName: String){
        try {
            val geocoder = Geocoder(requireContext(), Locale.getDefault())
            var geoResults: List<Address> = geocoder.getFromLocationName("$locationName", 1)
            if (geoResults.isNotEmpty()) {
                val addr = geoResults[0]
                val location = GeoPoint(addr.latitude, addr.longitude)
                moveCameraMap(location)
            }else{
                Toast.makeText(requireContext(),"Location Not Found",Toast.LENGTH_LONG)
            }
        } catch (e: java.lang.Exception) {
            print(e.message)
        }
    }
    

    in the function we can see the geocoder call getFromLocationName("location name", max result), and we got the lat and long.

    It's my solution and I hope someone can make it better. thanks for your help