最近公司需求要搞离线地图等一些需求,然后找了半天资料对比,决定使用mapbox来实现,理由开源,并且支持多端(Android,ios,web,pc)接入也简单。包含百度和高德大部分的功能。并且可扩展性也很高。
首先在使用之前我们需要放一个官方的链接地址把MapBox map for Android,
那就准备开始动手吧,在开始之前需要去官网先申请一个账号,申请一个token,
然后创建一个项目在string.xml中配置上token
<resources>
<string name="app_name">地图</string>
<string name="mapbox_access_token">your mapbox token</string>
</resources>
然后在AndroidManifest.xml中添加上权限
<!--网络状态-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--位置信息-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!--网络-->
<uses-permission android:name="android.permission.INTERNET" />
接下来就是添加依赖,我这边用的是9.2.1版本,目前支持到的是9.4.0
implementation 'com.mapbox.mapboxsdk:mapbox-android-sdk:9.2.1'
在项目的根目录gradle中添加如下配置
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
mavenCentral()
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenCentral()
google()
jcenter()
maven { url 'https://mapbox.bintray.com/mapbox' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
接下来就开始我们的第一个地图界面,在activity_main.xml中加入
<com.mapbox.mapboxsdk.maps.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
在activity中
private MapView mapView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.mapbox_access_token));
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {
mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
@Override
public void onStyleLoaded(@NonNull Style style) {
// Map is set up and the style has loaded. Now you can add data or make other map adjustments
}
});
}
});
}
到这里基本设置已经完成地图已经可以出来了