android - 如何在 Android Studio 中使用 Places API 在地图上显示多个位置标记
问题描述
在这里,我正在制作一个 android 应用程序,从 JSON 文件中检索纬度和经度。并在谷歌地图上显示标记。我想在我的地图上显示 1 公里半径内的所有附近医院。我还启用了 API。该地图显示 JSON 文件 URL,但不显示 google map 上的标记。我被困在这一点上,无法弄清楚代码的实际问题是什么。请帮助我解决这个错误或我犯的任何可能的错误。任何形式的帮助将不胜感激。提前致谢!
这是我的 JSON 文件。这个文件包括很多医院,所以我从我的 JSON 文件中只添加了 1 个医院数据
"results" : [
{
"business_status" : "OPERATIONAL",
"geometry" : {
"location" : {
"lat" : 33.6327965,
"lng" : 73.06251920000001
},
"viewport" : {
"northeast" : {
"lat" : 33.6341501802915,
"lng" : 73.0637985802915
},
"southwest" : {
"lat" : 33.63145221970851,
"lng" : 73.0611006197085
}
}
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/doctor-71.png",
"id" : "3fa0f9e5050e90cd8a160b8dbbf731f0759ea5fa",
"name" : "Healers Center Hospital",
"opening_hours" : {
"open_now" : true
},
"photos" : [
{
"height" : 4128,
"html_attributions" : [
"\u003ca href=\"https://maps.google.com/maps/contrib/105384437691919760909\"\u003eDr Sohail Malik\u003c/a\u003e"
],
"photo_reference" : "CmRaAAAAtd17x9IwXeQOQXbhagxoEVPCi6SutYfqz55JKAqyUGtE_Xj7nUSITFnOK2_tISls7rz7_oqikG4ffDWbqVKzGw15g1FjEDMfvJQnhWI_9kOC1dl-O3Qwc_aKA-7YvndyEhAfVnOscXsK0mTNiIBSYJTyGhSiP9tR_D1Rb-dEPAvvtgP4CjZmVQ",
"width" : 2322
}
],
"place_id" : "ChIJiZ8Z7-CU3zgRaH9qFQpj_xA",
"plus_code" : {
"compound_code" : "J3M7+42 Rawalpindi, Pakistan",
"global_code" : "8J5MJ3M7+42"
},
"rating" : 4.4,
"reference" : "ChIJiZ8Z7-CU3zgRaH9qFQpj_xA",
"scope" : "GOOGLE",
"types" : [ "hospital", "health", "point_of_interest", "establishment" ],
"user_ratings_total" : 7,
"vicinity" : "Saidpur Road, Rawalpindi"
},
这是我的 GetNearbyPlacesData 文件:
class GetNearbyPlacesData : AsyncTask<Any?, String, String>() {
private var googlePlacesData: String? = null
private var mMap: GoogleMap? = null
private var url: String? = null
override fun doInBackground(vararg objects: Any?): String? {
mMap = (objects.first() as Array<Object>)[0] as GoogleMap
url = (objects.first() as Array<Object>)[1].toString()
val downloadURL = DownloadUrl()
try{
googlePlacesData = downloadURL.readUrl(url!!)
} catch (e: IOException)
{
e.printStackTrace();
}
return googlePlacesData
}
override fun onPostExecute(s: String ) {
val nearbyPlaceList: List<HashMap<String, String>>
val parser = DataParser()
nearbyPlaceList = parser.parse(s)
showNearbyPlaces(nearbyPlaceList)
Log.d("nearby places data", nearbyPlaceList.toString());
}
private fun showNearbyPlaces(nearbyplaces: List<java.util.HashMap<String, String>>)
{
for (i in 0 until nearbyplaces.size) {
val markerOptions = MarkerOptions()
val googlePlace = nearbyplaces[i]
val PlaceName = googlePlace["place_name"]
val vicinity = googlePlace["vicinity"]
val lat = googlePlace["lat"]!!.toDouble()
val lng = googlePlace["lng"]!!.toDouble()
val latLng = LatLng(lat, lng)
markerOptions.position(latLng)
markerOptions.title("$PlaceName : $vicinity")
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
mMap!!.addMarker(markerOptions)
mMap!!.moveCamera(CameraUpdateFactory.newLatLng(latLng))
mMap!!.animateCamera(CameraUpdateFactory.zoomBy(12f))
}
}
}
这是我的 DataParser 类:
class DataParser {
private fun getPlace(googlePlaceJson:JSONObject):HashMap<String,String>{
val googlePlacesMap = HashMap<String,String>()
var placeName = "--NA--"
var vicinity = "--NA--"
var latitude = ""
var longitude = ""
var reference = ""
try {
if(!googlePlaceJson.isNull("name")) {
placeName = googlePlaceJson.getString("name")
}
if(!googlePlaceJson.isNull("vicinity")) {
vicinity = googlePlaceJson.getString("vicinity")
}
latitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lat")
longitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lng")
reference = googlePlaceJson.getString("reference")
googlePlacesMap["place_name"] = placeName
googlePlacesMap.put("vicinity", vicinity)
googlePlacesMap.put("lat", latitude)
googlePlacesMap.put("lng", longitude)
googlePlacesMap.put("reference", reference)
Log.d("Place Name", placeName)
}
catch (e: IOException){
e.printStackTrace()
}
return googlePlacesMap
}
private fun getPlaces(jsonArray: JSONArray):List<HashMap<String,String>>{
val count:Int = jsonArray.length()
val placesList = ArrayList<HashMap<String,String>>()
var placeMap: HashMap<String,String>
for (i in 0 until count){
try {
placeMap = getPlace(jsonArray.get(i) as JSONObject)
placesList.add(placeMap)
}
catch (e:JSONException){
e.printStackTrace()
}
}
return placesList
}
fun parse(jsonData: String):List<HashMap<String,String>>{
var jsonArray:JSONArray? = null
val jsonObject:JSONObject
try{
jsonObject = JSONObject(jsonData)
jsonArray = jsonObject.getJSONArray("results")
}
catch (e:JSONException) {
e.printStackTrace()
}
return getPlaces(jsonArray!!)
}
这是我的 downloadUrl 类:
class DownloadUrl {
@Throws(IOException::class)
fun readUrl(myUrl: String): String {
var data = ""
var inputStream: InputStream? = null
var urlConnection: HttpURLConnection? = null
try {
val url = URL(myUrl)
urlConnection = url.openConnection() as HttpURLConnection
urlConnection.connect()
inputStream = urlConnection.inputStream
val br = BufferedReader(InputStreamReader(inputStream!!))
val sb = StringBuffer()
val line = ""
while ((line == br.readLine()) != null)
sb.append(line)
data = sb.toString()
br.close()
} catch (e: MalformedURLException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
} finally {
inputStream!!.close()
urlConnection!!.disconnect()
}
Log.d("DownloadURL", "Returning data= $data")
return data
}
}
这是我的主文件,我使用这三个类在 Google 地图上显示标记:我没有为此活动添加完整代码,我只显示了与上面显示的三个类相关的代码。我没有在这里包含的其余部分是我当前的位置和权限请求
class SearchBloodBanks : AppCompatActivity(), OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener{
private lateinit var mMap: GoogleMap
private lateinit var mGoogleApiClient: GoogleApiClient
private var currentLatitude: Double = 0.0
private var currentLongitude: Double = 0.0
private lateinit var myLocation: Location
private val REQUEST_ID_MULTIPLIER_PERMISSION = 1
private val REQUEST_CHECK_SETTINGS_GPS = 2
var PROXIMITY_RADIUS = 1000
private var fusedLocationProviderClient: FusedLocationProviderClient? = null
private var currentLocationMarker: Marker? = null
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
mMap.uiSettings.setZoomControlsEnabled(true)
mMap.uiSettings.setMyLocationButtonEnabled(true)
mMap.uiSettings.setMapToolbarEnabled(true)
}
private fun getUrl(latitude: Double, longitude: Double, nearbyPlace: String ): String? {
val googlePlaceUrl = StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?")
googlePlaceUrl.append("location=").append(latitude).append(",").append(longitude)
googlePlaceUrl.append("&radius=").append(PROXIMITY_RADIUS)
googlePlaceUrl.append("&type=$nearbyPlace")
googlePlaceUrl.append("&sensor=true")
googlePlaceUrl.append("&key=" + resources.getString(R.string.places_api_key))
Log.d("NearbyHospitalActivity", "url = $googlePlaceUrl")
return googlePlaceUrl.toString()
}
override fun onLocationChanged(location: Location) {
myLocation = location
currentLatitude = location.latitude
currentLongitude = location.longitude
currentLocationMarker?.remove()
val latLng = LatLng(currentLatitude, currentLongitude)
val markerOptions = MarkerOptions()
markerOptions.position(latLng)
markerOptions.title("Current Location")
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
currentLocationMarker = mMap.addMarker(markerOptions)
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng))
mMap.animateCamera(CameraUpdateFactory.zoomBy(0F))
LocationServices.FusedLocationApi.removeLocationUpdates( mGoogleApiClient, this)
}
private fun ShowHospitals(latitude: Double, longitude: Double) {
val dataTransfer = arrayOfNulls<Any>(2)
val getNearbyPlacesData = GetNearbyPlacesData()
val url = getUrl(latitude, longitude, "hospital")
dataTransfer[0] = mMap
dataTransfer[1] = url
getNearbyPlacesData.execute(dataTransfer)
Toast.makeText(this, "Showing Nearby Hospitals", Toast.LENGTH_SHORT).show()
}
}