Google Map显示当前位置, 导航位置方向, 搜索位置等。要将Google Map放置在应用程序中, 我们需要创建Google Map API密钥并将其集成到我们的应用程序中。
使用Java代码的Google Map教程在Android Google Map上实现。
在本教程中, 我们将把Google Maps集成到我们的Android应用程序中。要将Google Map放置在应用程序中, 请选择活动类型作为Google Maps Activity。默认情况下, 此活动会生成Google地图所需的必需配置和设置。
文章图片
要实现Google Map, 我们需要生成Google Map API密钥并将其集成到我们的应用程序中。
复制res / values / google_map_api.xml文件中的网址, 并将其粘贴到浏览器中, 或者我们可以直接在Console Google Developer上访问以生成Google Map API密钥。
文章图片
单击创建API密钥以生成API密钥。
文章图片
单击创建API密钥后, 它将生成显示以下屏幕的我们的API密钥。
文章图片
将生成的API密钥粘贴到我们的res / values / google_map_api.xml文件中。
文章图片
activity_maps.xml
在activity_maps.xml布局文件中添加以下代码。
<
fragment xmlns:android="http://schemas.android.com/apk/res/android"xmlns:map="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/map"android:name="com.google.android.gms.maps.SupportMapFragment"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="example.srcmini.com.kotlingooglemap.MapsActivity" />
build.gradle
在build.gradle文件中添加Google Map Service和Google Location Service依赖项。
dependencies {implementation fileTree(include: ['*.jar'], dir: 'libs')implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"implementation 'com.android.support:appcompat-v7:26.1.0'implementation 'com.google.android.gms:play-services-maps:11.8.0'implementation 'com.google.android.gms:play-services-location:11.8.0'testImplementation 'junit:junit:4.12'}
strings.xml
<
resources>
<
string name="app_name">
Kotlin Google Map<
/string>
<
string name="title_activity_maps">
Map Fixed Location<
/string>
<
/resources>
google_map_api.xml
将Google Map API密钥放置在res / values / google_map_api.xml文件中。
<
resources>
<
!--Follow the directions here:https://developers.google.com/maps/documentation/android/signupOnce you have your key (it starts with "AIza"), replace the "google_maps_key"string in this file.-->
<
string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">
AIzaSyCmTF-n-REPLACE-WITH-YOUR-KEY<
/string>
<
/resources>
MapsActivity.kt
要在MapsActivity.kt类中获取GoogleMap对象, 我们需要实现OnMapReadyCallback接口并覆盖onMapReady()回调方法。要在地图上显示定位位置, 请将纬度和经度点放置在LatLng(纬度, 经度)中。
GoogleMap.addMarker()指向给定位置的位置。
package example.srcmini.com.kotlingooglemapimport android.os.Bundleimport android.support.v7.app.AppCompatActivityimport com.google.android.gms.maps.CameraUpdateFactoryimport com.google.android.gms.maps.GoogleMapimport com.google.android.gms.maps.OnMapReadyCallbackimport com.google.android.gms.maps.SupportMapFragmentimport com.google.android.gms.maps.model.LatLngimport com.google.android.gms.maps.model.Markerimport com.google.android.gms.maps.model.MarkerOptionsclass MapsActivity : AppCompatActivity(), OnMapReadyCallback, GoogleMap.OnMarkerClickListener {private lateinit var mMap: GoogleMapoverride 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 SupportMapFragmentmapFragment.getMapAsync(this)}/*** 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// Add a marker in India and move the cameraval myLocation = LatLng(20.5937, 78.9629)mMap.addMarker(MarkerOptions().position(myLocation).title("Marker in India"))mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation))mMap.uiSettings.isZoomControlsEnabled = true}override fun onMarkerClick(p0: Marker?) = false}
AndroidManifest.xml
在AndroidManifest.xml文件中添加。
<
?xml version="1.0" encoding="utf-8"?>
<
manifest xmlns:android="http://schemas.android.com/apk/res/android"package="example.srcmini.com.kotlingooglemap">
<
uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<
applicationandroid: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">
<
meta-dataandroid:name="com.google.android.geo.API_KEY"android:value="http://www.srcmini.com/@string/google_maps_key" />
<
activityandroid:name=".MapsActivity"android:label="@string/title_activity_maps">
<
intent-filter>
<
action android:name="android.intent.action.MAIN" />
<
category android:name="android.intent.category.LAUNCHER" />
<
/intent-filter>
<
/activity>
<
/application>
<
/manifest>
输出:
文章图片
MapsActivity.kt
【Kotlin Android Google Map固定位置】建立在Marshmallow版本上的应用程序有助于运行时用户权限。在此类中, 我们通过提供运行时权限访问设备精细位置ACCESS_FINE_LOCATION来创建上述示例。
package example.srcmini.com.kotlingooglemapimport android.Manifestimport android.content.pm.PackageManagerimport android.os.Buildimport android.os.Bundleimport android.support.v4.app.ActivityCompatimport android.support.v4.app.FragmentActivityimport android.widget.Toastimport com.google.android.gms.maps.CameraUpdateFactoryimport com.google.android.gms.maps.GoogleMapimport com.google.android.gms.maps.OnMapReadyCallbackimport com.google.android.gms.maps.SupportMapFragmentimport com.google.android.gms.maps.model.LatLngimport com.google.android.gms.maps.model.Markerimport com.google.android.gms.maps.model.MarkerOptionsclass MapsActivity : FragmentActivity(), OnMapReadyCallback, GoogleMap.OnMarkerClickListener{private lateinit var mMap: GoogleMapcompanion object {private val MY_PERMISSION_FINE_LOCATION = 101}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 SupportMapFragmentmapFragment.getMapAsync(this)}override fun onMapReady(googleMap: GoogleMap) {mMap = googleMap// Add a marker in India and move the cameraval india = LatLng(20.5937, 78.9629)mMap.addMarker(MarkerOptions().position(india).title("Marker in India"))mMap.moveCamera(CameraUpdateFactory.newLatLng(india))if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {mMap.isMyLocationEnabled = true}else {//condition for Marshmello and aboveif (Build.VERSION.SDK_INT >
= Build.VERSION_CODES.M) {requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), MY_PERMISSION_FINE_LOCATION)}}mMap.setOnMarkerClickListener(this)}override fun onMarkerClick(p0: Marker?) = falseoverride fun onRequestPermissionsResult(requestCode: Int, permissions: Array<
String>
, grantResults: IntArray) {super.onRequestPermissionsResult(requestCode, permissions, grantResults)when (requestCode) {MY_PERMISSION_FINE_LOCATION ->
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {//permission to access location grantif (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {mMap.isMyLocationEnabled = true}}//permission to access location deniedelse {Toast.makeText(applicationContext, "This app requires location permissions to be granted", Toast.LENGTH_LONG).show()finish()}}}}
输出:
文章图片
推荐阅读
- 使用URL的Kotlin Android JSON解析
- Kotlin Android Google地图搜索位置
- Android Firebase身份验证-Google登录
- Kotlin Android Google AdMob横幅广告示例
- Kotlin Android Google AdMob非页内广告示例
- Kotlin Android显式Intent
- Kotlin Android自定义Toast
- Kotlin Android自定义ListView
- Kotlin Android上下文菜单