Arcgis runtime for Android 加載在線地圖并緩存本地

上代碼,直接復(fù)制使用,只需配置其中的一些屬性即可

package com.zydl.leaderdecisionbozhou.map;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.util.Log;

import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.esri.arcgisruntime.arcgisservices.LevelOfDetail;
import com.esri.arcgisruntime.arcgisservices.TileInfo;
import com.esri.arcgisruntime.data.TileKey;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.SpatialReference;
import com.esri.arcgisruntime.layers.ImageTiledLayer;
import com.esri.arcgisruntime.mapping.Basemap;
import com.zydl.leaderdecisionbozhou.MyApplication;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Sch.
 * Date: 2020/9/10
 * description: 帶有緩存功能的切片圖層
 */
public class CacheTiledLayer extends ImageTiledLayer {
    private String mUrl;//地圖服務(wù)地址
    private static String CACHE_PATH;//緩存路徑

    private static SpatialReference SRID = SpatialReference.create(4326);//坐標(biāo)系
    //tileInfo
    private static int TILE_HEIGHT = 256;
    private static int TILE_WIDTH = 256;
    private static int DPI = 96;
    private static TileInfo.ImageFormat IMAGE_FORMAT = TileInfo.ImageFormat.PNG;
    private static Point sOriginPoint = new Point(-180, 90, SRID);
    //lods
    private static List<LevelOfDetail> sLevelOfDetails = new ArrayList<LevelOfDetail>() {
        {
            add(new LevelOfDetail(0, 1.40625, 591657527.594076));
            add(new LevelOfDetail(1, 0.703125, 295828763.797038));
            add(new LevelOfDetail(2, 0.3515625, 147914381.898519));
            add(new LevelOfDetail(3, 0.17578125, 73957190.949259));
            add(new LevelOfDetail(4, 0.087890625, 36978595.47463));
            add(new LevelOfDetail(5, 0.0439453125, 18489297.737315));
            add(new LevelOfDetail(6, 0.02197265625, 9244648.868657));
            add(new LevelOfDetail(7, 0.010986328125, 4622324.434329));
            add(new LevelOfDetail(8, 0.005493164062, 2311162.217164));
            add(new LevelOfDetail(9, 0.002746582031, 1155581.108582));
            add(new LevelOfDetail(10, 0.001373291016, 577790.554291));
            add(new LevelOfDetail(11, 0.000686645508, 288895.277146));
            add(new LevelOfDetail(12, 0.000343322754, 144447.638573));
            add(new LevelOfDetail(13, 0.000171661377, 72223.819286));
            add(new LevelOfDetail(14, 0.000085830688, 36111.909643));
            add(new LevelOfDetail(15, 0.000042915344, 18055.954822));
            add(new LevelOfDetail(16, 0.000021457672, 9027.977411));
            add(new LevelOfDetail(17, 0.000010728836, 4513.988705));
            add(new LevelOfDetail(18, 0.000005364418, 2256.994353));
        }
    };
    private static Envelope sEnvelope = new Envelope(115.7058620453, 33.7499141693, 115.8587265015, 33.9134216309, SRID);

    /**
     * @param context 上下文
     * @param url     地圖地址
     * @return Basemap
     */
    public static Basemap creatBaseMap(Context context, String url) {
        //去水印
        ArcGISRuntimeEnvironment.setLicense("runtimelite,1000,rud4449636536,none,NKMFA0PL4S0DRJE15166");
        TileInfo tileInfo = new TileInfo(DPI, IMAGE_FORMAT,
                sLevelOfDetails, sOriginPoint, SRID, TILE_HEIGHT, TILE_WIDTH);
        Basemap basemap = new Basemap();
        basemap.getBaseLayers().add(new CacheTiledLayer(context, url, tileInfo, sEnvelope));
        return basemap;
    }

    private CacheTiledLayer(Context context, String url, TileInfo tileInfo, Envelope envelope) {
        super(tileInfo, envelope);
        this.mUrl = url;
        //判斷SD卡是否可用
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            CACHE_PATH = context.getExternalFilesDir("MapCache").getAbsolutePath();
        } else {
            //沒內(nèi)存卡就存機身內(nèi)存
            CACHE_PATH = context.getFilesDir() + File.separator + "MapCache";
        }
        File file = new File(CACHE_PATH);
        if (!file.exists()) {//判斷文件目錄是否存在
            file.mkdirs();
        }
    }

    @Override
    protected byte[] getTile(TileKey tileKey) {
        int level = tileKey.getLevel();
        int col = tileKey.getColumn();
        int row = tileKey.getRow();
        // 若緩存存在則返回緩存字節(jié)
        String fileName = col + "_" + row + ".png";
        if (hasCached(level + "", fileName)) {
            //本地存在
            File _cacheLevelDir = new File(CACHE_PATH + "/" + level);
            byte[] cachedBytes = null;
            for (File _file : _cacheLevelDir.listFiles()) {
                if (_file.getName().equals(fileName)) {
                    cachedBytes = new byte[(int) _file.length()];
                    try {
                        FileInputStream _fis = new FileInputStream(_file);
                        _fis.read(cachedBytes);
                        _fis.close();
                        return cachedBytes;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        //本地不存在,從網(wǎng)絡(luò)加載
        if (isNetworkConnected()) {
            byte[] result = downloadData(level, row, col);
            return result;
        }
        return null;
    }

    /**
     * 判斷是否有緩存數(shù)據(jù)
     *
     * @param level    級別
     * @param fileName 瓦片名稱  row_col.png
     * @return
     */
    private boolean hasCached(String level, String fileName) {
        File _cacheLevelDir = new File(CACHE_PATH + "/" + level);
        if (!_cacheLevelDir.exists()) {
            _cacheLevelDir.mkdir();
            return false;
        }
        for (File _file : _cacheLevelDir.listFiles()) {
            if (_file.getName().equals(fileName)) {//存在同名文件
                try {
                    byte[] cachedBytes = new byte[(int) _file.length()];
                    FileInputStream _fis = new FileInputStream(_file);
                    _fis.read(cachedBytes); //文件可讀
                    _fis.close();
                    return true;
                } catch (Exception e) {
                    //文件不可讀
                    return false;
                }
            }
        }
        //不存在同名文件
        return false;
    }

    /**
     * 是否有網(wǎng)絡(luò)
     * 需要權(quán)限 ACCESS_NETWORK_STATE
     *
     * @return true  or   false
     */
    public static boolean isNetworkConnected() {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) MyApplication.getInstance()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo != null) {
            return mNetworkInfo.isAvailable();
        }
        return false;

    }

    /**
     * 從網(wǎng)絡(luò)加載瓦片,并保存本地
     *
     * @param level 級別
     * @param row   行
     * @param col   列
     * @return 瓦片數(shù)據(jù)
     */
    private byte[] downloadData(int level, int row, int col) {
        byte[] result = null;
        try {
            URL url = new URL(mUrl + "/tile/" + level + "/" + row + "/" + col);
            byte[] buf = new byte[1024];
            HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.connect();
            BufferedInputStream is = new BufferedInputStream(httpConnection.getInputStream());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int temp = -1;
            while ((temp = is.read(buf)) > 0) {
                bos.write(buf, 0, temp);
            }
            is.close();
            httpConnection.disconnect();
            result = bos.toByteArray();
            saveMapCache(result, col + "_" + row + ".png", level + "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 保存瓦片本地
     *
     * @param bytes    瓦片數(shù)據(jù)
     * @param fileName 瓦片命名
     * @param level    級別
     */
    private void saveMapCache(byte[] bytes, String fileName, String level) {
        try {
            File _cacheDir = new File(CACHE_PATH);
            if (!_cacheDir.exists()) {
                _cacheDir.mkdir();
            }
            File _cacheLevelDir = new File(CACHE_PATH + "/" + level);
            if (!_cacheLevelDir.exists()) {
                _cacheLevelDir.mkdir();
            }
            File _cacheFile = new File(_cacheLevelDir, fileName);
            _cacheFile.createNewFile();
            FileOutputStream _fos = new FileOutputStream(_cacheFile);
            _fos.write(bytes);
            _fos.close();
        } catch (IOException e) {
            Log.e("mapCache", "saveMapCache:" + e.toString());
        }
    }
}

其中
image.png

這些數(shù)據(jù)要根據(jù)地圖服務(wù)中的參數(shù)去配置,
用瀏覽器打開地圖服務(wù),如下


image.png

替換參數(shù)即可

使用

        ArcGISMap arcGISMap = new ArcGISMap();
        arcGISMap.setBasemap(CacheTiledLayer.creatBaseMap(this, 地圖服務(wù)地址));
        mMapView.setMap(arcGISMap);

說明:根據(jù)應(yīng)用規(guī)范,緩存文件存儲在SDCard/Android/data/你的應(yīng)用的包名/files/ 目錄下,不用動態(tài)申請權(quán)限,只需在清單文件中聲明即可,卸載后會一并刪除,凈化安卓文件環(huán)境,人人有責(zé)

image.png

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容