上网查了一些资料发现有关谷歌地图sdk集成的文章还是不少的,但是都缺乏系统性。这里做些系统整理,主要分以下篇幅讲解,希望对初始谷歌地图的你有所帮助:
- 【谷歌地图–集成准备】
- 【谷歌地图–MapsSDK集成】
- 【谷歌地图–DirectionsSDK集成】
- 【谷歌地图–PlacesSDK集成】
开始正文啦:
由于众所周知的的原因,集成谷歌地图sdk前首先你的pc端和移动端都是要翻墙的,不然后续的一些功能你都无法操作。
谷歌地图–MapsSDK集成
相信经过 谷歌地图–集成准备 这篇文章,一些准备工作你基本差不多了,api_key也申请好了。
依赖添加
implementation 'com.google.android.gms:play-services-maps:17.0.0'
基本地图展示
废话不多说,咱们先上效果图:
布局文件:
<fragmentandroid:id="@+id/map"android:name="com.google.android.gms.maps.SupportMapFragment"android:layout_width="match_parent"android:layout_height="match_parent" />
关键代码:
class ExampleActivity : AppCompatActivity(), OnMapReadyCallback {private val TAG = "ExampleActivity"private lateinit var mGoogleMap: GoogleMap//富华游乐园val strOrigin = "36.71525382744859,119.16037559509276"val appointLoc = LatLng(strOrigin.split(",").toTypedArray()[0].toDouble(),strOrigin.split(",").toTypedArray()[1].toDouble());override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_example)val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?mapFragment!!.getMapAsync(this)}override fun onMapReady(mGoogleMap: GoogleMap?) {this.mGoogleMap = mGoogleMap ?: return;with(mGoogleMap) {// 移动地图到指定经度的位置moveCamera(CameraUpdateFactory.newLatLngZoom(appointLoc, 15f))//添加标记到指定经纬度addMarker(MarkerOptions().position(appointLoc).title("富华游乐园").snippet("$appointLoc")//设置谷歌地图自带的图标样式.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))//设置本地资源图标//.icon(BitmapDescriptorFactory.fromResource(R.drawable.baseline_change_history_red_a700_24dp))).showInfoWindow() //显示信息窗口}}}
到这里一个基本的地图展示,你已经完成啦!
定位
如果想添加定位功能的话,还需要添加这行依赖:
implementation 'com.google.android.libraries.places:places:2.4.0'
废话不多说,咱们先上效果图:
发起定位
关键代码:
private fun getDeviceLocation() {val selfPermission4 =ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)if (selfPermission4 != PackageManager.PERMISSION_GRANTED) {ActivityCompat.requestPermissions(this,arrayOf(Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_BACKGROUND_LOCATION),12)return} else {Log.i(TAG, "getDeviceLocation: 已有权限")}mGoogleMap.isMyLocationEnabled = truemGoogleMap.uiSettings?.isMyLocationButtonEnabled = true//这行代码,就能发起定位请求val locationResult = fusedLocationProviderClient.lastLocation//监听定位结果locationResult.addOnCompleteListener(this) { task ->if (task.isSuccessful) {// Set the map's camera position to the current location of the device.var lastKnownLocation = task.resultif (lastKnownLocation != null) {Log.i(TAG, "getDeviceLocation: locationResult if")} else {Log.i(TAG, "getDeviceLocation: locationResult else")}} else {Log.e(TAG, "Exception: %s", task.exception)}}mGoogleMap!!.setOnMyLocationButtonClickListener {//返回 false,这样我们就不会使用该事件,而默认行为仍然会发生println("MainActivity.getDeviceLocation ddd")false}}
实时定位
/*** 监听位置变化*/private fun monitorLocationChange() {val selfPermission4 =ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)if (selfPermission4 != PackageManager.PERMISSION_GRANTED) {ActivityCompat.requestPermissions(this,arrayOf(Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_BACKGROUND_LOCATION),12)return} else {Log.i(TAG, "monitorLocationChange: 已有权限")}val request = LocationRequest()request.priority = LocationRequest.PRIORITY_HIGH_ACCURACY//设置间隔request.setInterval(3000)//最快间隔request.fastestInterval = 3000//更新的次数哦//request.numUpdates=1mLocationCallback = object : LocationCallback() {override fun onLocationResult(locationResult: LocationResult?) {val lastLocation = locationResult?.lastLocationif (lastLocation != null) {Log.i(TAG, "onLocationResult: 监听位置变化结果")val curPosition = LatLng(lastLocation.latitude,lastLocation.longitude)mGoogleMap!!.animateCamera(CameraUpdateFactory.newLatLng(curPosition))} else {Log.i(TAG, "onLocationResult: 监听位置变化结果 lastLocation is null")}}}fusedLocationProviderClient.requestLocationUpdates(request,mLocationCallback,Looper.myLooper())}override fun onDestroy() {super.onDestroy()//停止获取位置更新if (mLocationCallback != null) {fusedLocationProviderClient.removeLocationUpdates(mLocationCallback)}}
到这里定位相关的功能,相信你也基本掌握啦。不过喜欢举一反三的同学,此时会想了,截图中定位蓝点图标我想换成自己的怎么办呢,以及换成自己的图标后,蓝点的方向变化又要如何处理呢?不要着急,带着你的疑问,继续看完后续的文章吧,哈哈。
地图点击事件
mGoogleMap.setOnMapClickListener { latLng: LatLng? ->Log.i(TAG, "onMapReady: 地图点击事件")}mGoogleMap.setOnMapLongClickListener { latLng ->Log.i(TAG, "onMapReady: 地图长按点击事件")}mGoogleMap.setOnMarkerClickListener(object : GoogleMap.OnMarkerClickListener {override fun onMarkerClick(mMarker: Marker?): Boolean {Log.i(TAG, "onMapReady: Marker点击事件")return false}})mGoogleMap.setOnInfoWindowClickListener { mMarker ->Log.i(TAG, "onMapReady: Marker 弹窗点击事件")}mGoogleMap.setOnPoiClickListener(object : GoogleMap.OnPoiClickListener {override fun onPoiClick(mPointOfInterest: PointOfInterest?) {Log.i(TAG, "onMapReady: Poi 点击事件")}})
参考博客:
官方文档:
https://developers.google.com/maps/documentation/android-sdk/intro
官方demo:
- android-samples
- android-places-demos
- android-maps-utils
拾取坐标系统
【谷歌地图–番外篇 android-maps-utils的使用 】