Карта Google не отображается, в эмуляторе отображается только логотип Google. - PullRequest
0 голосов
/ 11 мая 2018

У меня возникла проблема с загрузкой действия на карте. Когда я пытаюсь запустить приложение, в действии на карте внизу отображается только логотип Google, но нет признаков карты, как показано на рисунке ниже.Я не знаю, почему это происходит, потому что я включил gps и подключился к интернету, а также использую ключ API карты. Вот мой код файла манифеста

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.abdus.touristswatch">

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality. 
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
     <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".Controller.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Controller.selection" />
        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/. 
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyBJJpVVf6DZcQrl-*************" />

        <activity
            android:name=".Controller.MapsActivity"
            android:label="@string/title_activity_maps"></activity>
    </application>

</manifest>

, а теперь это код активности

package com.example.abdus.touristswatch.Controller

import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import com.example.abdus.touristswatch.R

import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import java.util.jar.Manifest

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
     var locationManager:LocationManager?=null
    var locationListener:LocationListener?=null
    private lateinit var mMap: GoogleMap

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_maps)
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        val mapFragment = supportFragmentManager
                .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if(grantResults.size>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED ){

            if(ContextCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
                locationManager!!.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0f,locationListener)
                var location:Location=locationManager!!.getLastKnownLocation(LocationManager.GPS_PROVIDER)
                updateMap(location)

               }


        }


    }

    fun updateMap(location:Location){
        val userLocation = LatLng(location.getLatitude(), location.getLongitude())
         mMap.clear()
        mMap.addMarker(MarkerOptions().position(userLocation).title("Your Location"))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation))
    }
    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap
         locationManager=getApplicationContext().getSystemService(Context.LOCATION_SERVICE) as LocationManager
         locationListener=(object:LocationListener{
             override fun onLocationChanged(location: Location?) {
                 updateMap(location!!)
             }

             override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {

             }

             override fun onProviderEnabled(provider: String?) {

             }

             override fun onProviderDisabled(provider: String?) {

             }

         })
          if(Build.VERSION.SDK_INT<23){
              if(ContextCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
              locationManager!!.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0f,locationListener)}
          }
          else{
              if(ContextCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
                 var permissionlist=arrayOf<String>(android.Manifest.permission.ACCESS_FINE_LOCATION)
                  ActivityCompat.requestPermissions(this,permissionlist,1)
              }
              else{
                  locationManager!!.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0f,locationListener)
                  var location:Location=locationManager!!.getLastKnownLocation(LocationManager.GPS_PROVIDER)
                  updateMap(location)

              }
          }

        // Add a marker in Sydney and move the camera

    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...