kotlin实现高德地图代码
时间: 2023-07-03 15:11:20 浏览: 100
Android Kotlin开发高德地图
以下是 Kotlin 实现高德地图的代码示例:
```kotlin
// 引入高德地图 SDK
import com.amap.api.maps.MapView
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.MarkerOptions
// 在 Activity 中初始化地图
class MapActivity : AppCompatActivity() {
private lateinit var mapView: MapView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map)
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
// 获取地图对象
val aMap = mapView.map
// 添加标记
val latLng = LatLng(39.906901,116.397972)
val markerOptions = MarkerOptions()
.position(latLng)
.title("Marker Title")
.snippet("Marker Snippet")
aMap.addMarker(markerOptions)
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
}
```
需要注意的是,这里的 `MapView` 是高德地图 SDK 中提供的地图视图,需要在布局文件中添加:
```xml
<com.amap.api.maps.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
还需要在 `AndroidManifest.xml` 文件中申请高德地图 SDK 的权限:
```xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
```
阅读全文