前一段使用了微信的地图,非常的好用。但是存在的问题是海外无法使用,出国就不能用了;
其实国内三家:百度,高德,微信都是一样的问题,当涉及到商业使用的时候需要付费;
国外除了谷歌还有一个选择,OpenSteetMap,这里记录一下使用流程。
1)模块的build.gradle添加
dependencies {
implementation 'org.osmdroid:osmdroid-android:6.1.11'
}
2)AndroidManifest.xml中添加依赖
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
3)布局文件中添加地图的占位的控件:
<!-- MAP -->
<org.osmdroid.views.MapView
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="test"
android:visibility="visible" />
4)主文件初始化中添加,
// MainActicity.kt
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// set user agent to prevent getting banned from the osm servers
Configuration.getInstance().userAgentValue = BuildConfig.APPLICATION_ID
// 缓存路径,在应用程序目录下 ,设置nl在根目录下(e.g. tile cache)
Configuration.getInstance().osmdroidBasePath = //File("/trackbook/mapdata/")
this.getExternalFilesDir(null)
5) Fragment中添加初始化函数
fun initMap(){
val mapView = binding.map
val controller = mapView.controller
mapView.isTilesScaledToDpi = true
mapView.setTileSource(TileSourceFactory.MAPNIK)
//mapView.setTileSource(TileSourceFactory.OpenTopo)
mapView.setMultiTouchControls(true)
mapView.zoomController.setVisibility(org.osmdroid.views.CustomZoomButtonsController.Visibility.SHOW_AND_FADEOUT)
val zoomLevel = 11.0
controller.setZoom(zoomLevel)
val compassOverlay = CompassOverlay(context, InternalCompassOrientationProvider(context), mapView)
compassOverlay.enableCompass()
// compassOverlay.setCompassCenter(36f, 36f + (statusBarHeight / densityScalingFactor)) // TODO uncomment when transparent status bar is re-implemented
compassOverlay.setCompassCenter(36f, 36f)
mapView.overlays.add(compassOverlay)
val animated = true
val position = GeoPoint(40.0, 116.0)
when (animated) {
true -> controller.animateTo(position)
false -> controller.setCenter(position)
}
}
编译运行即可;
我在手机上直接运行,方便使用clash设置网络,我最近发现真机调试比模拟器好用多了。