众所周知,Kotlin是一门与Swift类似的静态类型JVM语言,由JetBrains设计开发并开源。与Java相比,Kotlin的语法更简洁、更具表达性,而且提供了更多的特性。本人刚学习没多久,于是尝试着用kotlin实现百度地图覆盖物。
首先androidstudio 要进行kotlin开发,需要安装Kotlin和Kotlin Extensions。
其次 在build.gradle中配置:
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
为了防止在64位android手机上的崩溃,还需要:
ndk { abiFilters "armeabi", "armeabi-v7a", "x86", "mips"}
1.首先在app中初始化百度地图:
class App : Application() {
override fun onCreate() {
super.onCreate()
SDKInitializer.initialize(this)
}
}
2.加入import kotlinx.android.synthetic.main.activity_map.*,这样可以不用写findviewbyid
地图界面代码如下:
class MapActivity : AppCompatActivity() {
internal var mBaiduMap: BaiduMap? = null
private var mMarker: Marker? = null
private var mInfoWindow: InfoWindow? = null
override fun onCreate(arg0: Bundle?) {
super.onCreate(arg0)
setContentView(R.layout.activity_map)
initViews()
}
fun initViews() {
// 地图初始化
mBaiduMap = mMapView.map
mBaiduMap!!.setMapStatus(MapStatusUpdateFactory.zoomTo(20.0f))
val result = LatLng(34.827503, 113.549977)
mMarker = mBaiduMap!!.addOverlay(MarkerOptions().position(result).
icon(BitmapDescriptorFactory.fromResource
(R.drawable.icon_gcoding))) as Marker
mBaiduMap!!.setMapStatus(MapStatusUpdateFactory.newLatLng(result))
val location = TextView(this)
location.setBackgroundResource(R.mipmap.popup)
location.setPadding(30, 20, 30, 50)
location.setTextColor(resources.getColor(R.color.text_color1)) location.text = "郑州大学盛和苑"
mInfoWindow = InfoWindow(location, mMarker!!.position, -87)
mBaiduMap!!.setOnMarkerClickListener {
mBaiduMap!!.showInfoWindow(mInfoWindow)
true
}
}
override fun onPause() {
mMapView!!.onPause()
super.onPause()
}
override fun onResume() {
mMapView!!.onResume()
super.onResume()
}
override fun onDestroy() {
mMapView!!.onDestroy()
super.onDestroy()
}
}
网友评论