2017年11月12日 星期日

HTML2Canvas:用Javascript來做螢幕截圖

HTML2Canvas專案位置: https://html2canvas.hertzen.com/


簡介: HTML2Canvas(以下簡稱H2C)是一個Javascript工具用來將HTML元素轉換成Canvas,這樣就能很容易的把元素轉換成圖檔


簡單的範例

擷取整個網頁,並且將結果顯示在當前網頁上
html2canvas(document.body, {
  onrendered: function(canvas) {
    document.body.appendChild(canvas);
  }
});
擷取整個網頁並只取從左上角開始300x300的畫面,並且將結果顯示在當前網頁上
html2canvas(document.body, {
  onrendered: function(canvas) {
    document.body.appendChild(canvas);
  },
  width: 300,
  height: 300
});
在上面兩個範例可以看到一個很主要的事件叫做onrendered,這個事件會在完成擷取所指定之元素之後被觸發,也就是可以針對擷取結果(Canvas)做操作的地方。

如何下載擷取結果

這個工具的擷取結果是Canvas,所以只需要用Canvas本身的匯出功能就可以了(Canvas支援輸出jpeg, png)

html2canvas(document.body, {
  onrendered: function(canvas) {
    var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); //結果會是被Base64編碼後的圖片,但是要觸發下載必須先把型態改成octet-stream(用來騙瀏覽器而已,它還是png格式)
    window.location.href = image;
  }
});

Troubleshooting: 怎麼辦!!!SVG沒辦法被截取

SVG因為某些原因讓H2C沒辦法正常的擷取,解決方案就是用canvg先把SVG轉成Canvas之後再一起擷取

2016年10月8日 星期六

Simple Location Sender: 團隊動態追蹤的好範例


這個是什麼? What



這是一個使用者GPS位置回報系統的App端範例



為什麼需要這個? Why



這個範例嘗試用最簡單的方式來撰寫,也因此不論是修改還是學習都非常容易



什麼地方會用到? Where



當你在開發任何需要使用者回報地理位置給伺服器的應用



什麼時候會用到? When



在處理使用者回報資訊給伺服器的時候



誰會需要? Who



任何想要開發相關追蹤應用的開發者或著任何對於使用者端與伺服器端之間溝通有興趣的人



這個如何實作的? How



Project: https://github.com/lienching/LocationReportSender


這個範例使用了幾個開源函式庫
  • geojson : 用來處理 json
  • okhttp3 : 用來處理網路操作
  • realm : 資料庫

這整個範例可以分為四個部份
  1. LocationManager : 負責處理GPS位置,這樣就能得到使用者的位置
  2. JSONBuilder : 建立JSON檔,作為與伺服器溝通的格式
  3. TrackingService : 讓使用者位置的發送可以在Background執行
  4. BookMark(BookMarkHolder) : 這個範例使用Realm作為背後的資料庫,並使用AutoCompleteTextView來實現書籤選單,這個範例也支援將書籤輸入與輸出(格式為csv)

2016年6月12日 星期日

地圖圖層隨便你疊,地圖樣式你決定 - TileStache (基本介紹篇)


前言Preface



使用OpenStreetMap有一個很大的優勢,就是基本上地圖的樣式都是可以自主來去做定義。 但是其實OpenStreetMap原本的自訂圖塊( Custom Tiles ) 並不是我們想像中的那麼的容易操作而且有其限制( 沒辦法將多圖層合併為單一圖層,資源消耗大 ),但是感謝廣大的開源社群相關的工具如雨後春筍一般的一個個冒出來( 如 TileCache, OpenLayer , TileStache ),讓 OpenStreetMap 的地圖多樣性有了革命性的改變,因為可以將多圖層合併在雲端完成,也就可以讓設計者與地圖製作者們可以專心繪製自己的圖層,剩下的合併交給那些工具就好。

TileStache介紹
Brief introduction of TileStache



這次要介紹的TileStache它的前身是TileCache,它們都是用來做圖層渲染(多圖層渲染成一個),這對於設計者與地圖製作者都非常的方便,當然對於一些效能不太好的客戶端也可以帶來一些不錯的效能提升,而TileStache的設計目的是為了讓整個工具更貼近設計者與地圖製作者,讓它們可以在越少的步驟中產生他們所需要的東西。


TileStache設定
Installation of TileStache




TileStache取得請到 官網 or My Github , 目前這個工具只能用在Linux或OSX上


TileStache 是以Python做為開發語言,所以我們所需要的套件如下:




TileStache兩種使用方式:


  1. 直接用Script資料夾內的python script
    # 用來啟動伺服器(服務)
    tilestache-server.py
    
    # 用來快取圖檔(網路圖資)
    tilestache-seed.py
    
    # 用來產生自定義圖層
    tilestache-render.py
    
  2. 將tilestache工具加入指令集
    python setup.py install
    



從TileStache取得圖塊
Requesting Tiles from TileStache




  • 從 HTTP 取得
    1. 取得單一圖塊 Single Tile
      格式 : /{圖層名稱}/{縮放等級}/{x}/{y}.{副檔名(e.g. png, jpg}
      範例 : http://example.org/osm/12/656/1582.png
    2. 動態地圖(類似Google Map)
      格式 : /{圖層名稱}/preview.html
      範例 : http://example.org/osm/preview.html

  • 使用TileStache的API
    1. TileStache.getTile(layer, coord, extension[, ignore_cached=FALSE]): 直接取得圖塊 Get Tile Directly
      • layer: 想要取得得圖層( Core.Layer )
      • coord: 傳入所要取得的位置( ModestMaps.Core.Coordinate )
      • extension: 副檔名("jpg", "png") (String)
      • ignore_cached: (可有可無,預設為FALSE)是否忽略快取圖塊 (Boolean) 
    2. TileStache.requestHandler(config, path_info[,query_string=None][, script_name='']): 透過HTTP Requesting取得圖塊 Get Tile by HTTP Requesting
      • config: JSON設定檔的路徑(String) 或 TileStache.Config.Configuration物件(需要 cache, layers, dirpath 三個參數)
      • path_info: 傳入Request URL, 格式同從HTTP取得之取得單一圖塊(範例: /osm/12/656/1582.png )
      • query_string: (可有可無,預設為None)使用 JSONP 才會用到
      • script_name: (可有可無,預設為'') 給CGI的腳本,用來判斷是否轉址成功

2016年4月7日 星期四

創造自己的App市集( Using F-Droid )


介紹Introduction


F-Droid根據官方說法是一個在Android平台上的FOSS(Free and Open Source Software 免費與開源軟體)可安裝目錄程式,顧名思義就是非常類似我們所熟知了App市集囉。
那肯定會有人問說,既然有了Google Play為什麼還要另外自己去建立一個市集呢? 那是因為有些地方是沒辦法連得上Google Play,或著不喜歡目前市面上所有App市集的上架規則。 那用F-Droid架自己的市集有什麼好處呢?
  • 私人的程式庫,小小程式樂園
  • 自己的市集,自己說的算
  • 開源軟體,自己的模式自己建立



環境建立Setup



首先一定是要下載好工具囉

  • Linux

  • 有套件管理工具的好處就是一件完成安裝!

     sudo apt-get install fdroidserver
    

    當然還有一些進階的操作,例如如果有希望讓F-Droid自己把Source code編譯起來的話,可以用以下的指令(假設你什麼都沒有...)

    # 安裝一些用來編譯程式程式的套件
    sudo apt-get install openjdk-7-jdk libstdc++6:i386 libgcc1:i386 zlib1g:i386 libncurses5:i386 
    # 從android官網用wget抓android-sdk
    cd ~
    # 筆者目前最新版本是r24.4.1,建議讀者到 ( http://developer.android.com/sdk/index.html#Other ) 去查看最新的SDK
    wget http://dl.google.com/android/android-sdk_r24.4.1-linux.tgz
    # 用tar解壓縮我們剛剛的檔案
    tar zxcf android-sdk_r24.4.1-linux.tgz
    # 接下來我們要把ANDROID_HOME設定起來(假設你解壓縮出來的資料夾名字為 android-sdk-linux )
    export ANDROID_HOME=~/android-sdk-linux
    # 再來就是要把ANDROID_HOME丟進我們的 .bashrc (如果是zsh就會是 .zshrc ) 這樣我們的設定就會被記錄住了
    echo 'export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools' >> .bashrc
    

    還有其他一些有的沒有的選項設定,可以參考這邊

  • OSX

  • Using MacPorts

    port install fdroidserver
    

    Using HomeBrew

    brew install fdroidserver
    

    Using easy_install

    sudo easy_install fdroidserver
    
  • Windows

  • Windows基本上Command-Line base的東西就蠻殘缺的所以會需要借助Cygwin,不囉嗦~建立方式如下

    1. 下載 Cygwin (載點)
    2. 安裝 Cygwin , 並在選擇安裝套件的時候選擇安裝以下套件
      • gcc-core
      • git
      • openssh
      • python
      • python-pyasn1
      • python-imaging
      • python-magic
      • python-paramiko
      • python-requests
      • python-setuptools
      • rsync
      • wget
    3. 開啟一個Cygwin的bash介面,然後輸入
    4. easy_install fdroidserver
      
  • From Source

  •  git clone https://gitlab.com/fdroid/fdroidserver.git
     cd fdroidserver
     virtualenv --system-site-packages env/
     . env/bin/activate
     pip install -e .
     python setup.py install
    

接下來就是建立環境囉 (用Linux做示範)

# 伺服器這邊筆者選用Nginx,當然Apache Web Server也是可以
sudo apt-get install nginx
# 建立F-Droid專用的資料夾
sudo mkdir /usr/share/nginx/www/fdroid
sudo chown -R $USER /usr/share/nginx/www/fdroid
cd /usr/share/nginx/www/fdroid
# 初始化環境
fdroid init

然後在當前的資料夾裡面就會多了一個repo的資料夾,這邊就是我們放程式(.apk)的地方,程式放完就可以輸入下面的指令,來產生MetaData(程式敘述資料)

fdroid update --create-metadata

這樣我們的 Repo Server 已經建立完成囉~ 接下來把位置放進F-Droid的Client就可以連接到了



Config.py 設置


基本上要改的就這幾個

# Repo Server的網址
repo_url = "https://MyFirstFDroidRepo.org/fdroid/repo"
# Repo Server的名字
repo_name = "My First F-Droid Repo Demo"
# Repo Server的Icon
repo_icon = "fdroid-icon.png"
# Repo Server的敘述
repo_description = ""

改完之後要重置伺服器,用下方的指令

fdroid server update -v

2016年3月5日 星期六

Step By Step 簡易Mapsforge App開發:MapUpdateManager


目標Achievements


這個類別是用來做圖資更新檢查與更新


程式碼Code


package lien.ching.maptracker.api;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import lien.ching.maptracker.Constant;

/**
 * Created by lienching on 12/1/15.
 * In this class, I had no idea how to update a file by using DownloadManager
 * so I just try to use standard HTTP Download as the method
 */
public class MapUpdateManager extends AsyncTask {

    private ProgressDialog dialog;
    private PowerManager.WakeLock wakeLock;
    private Context context;
    private Activity activity;
    public MapUpdateManager(Context context, Activity activity){
        super();
        this.activity = activity;
        this.context = context;
    }
    @Override
    protected Boolean doInBackground(String... params) {
        //For Details, please check http://stackoverflow.com/a/3028660
        String continent = params[1];
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        File outputFile = new File(Constant.PATH_MAPSFORGE+params[0]);
        try{
            URL url = new URL("http://download.mapsforge.org/maps/"+params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            if(connection.getResponseCode() != HttpURLConnection.HTTP_OK){
                Toast.makeText(context,"Connection Fail..."+connection.getResponseCode(),Toast.LENGTH_SHORT).show();
                return false;
            }
            input = connection.getInputStream();


            if (outputFile.lastModified() < connection.getLastModified()){ //if the date is older than the latest file then close the download process
                input.close();
                output.close();
                return true;
            }
            dialog.setMessage("Map Source Updating");
            outputFile.delete();
            outputFile.createNewFile();
            output = new FileOutputStream(outputFile);
            byte data[] = new byte[8192];
            int count;
            while((count = input.read(data)) != -1){
                if(isCancelled()){
                    input.close();
                    return false;
                }

                output.write(data,0,count);
            }
        }catch (Exception e){
            Log.e("MapDownloadManager","Writing Data:"+e.toString());
            return false;
        }finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();

            } catch (IOException ignored) { }

            if (connection != null)
                connection.disconnect();
        }
        return false;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        PowerManager pm = (PowerManager) activity.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, activity.getClass().getName());
        wakeLock.acquire();
        dialog = new ProgressDialog(activity);
        dialog.setMessage("Map Source Checking");
        dialog.setCancelable(false);
        dialog.setIndeterminate(true);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.show();
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        if(dialog.isShowing()){
            dialog.dismiss();
        }
        if(wakeLock.isHeld())
            wakeLock.release();
        try {
            if (!aBoolean)
                Toast.makeText(context, "Download error", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
        }
        catch (Exception e){
            Log.d("MapUpdateManager", e.toString());
        }
    }
}



說明Explanation


這個整體程式使用的下載方式請參照這裡
這邊程式運作的方式是Async,可以在這邊瞭解更多
第57~61行:檢查圖資是不是比資料庫的還要舊,如果是就不繼續做更新的動作,否則就繼續做

Step By Step 簡易Mapsforge App開發:EnvCheck


目標Achievements


這個類別的工作是去偵測使用者是否有我們所需的地圖資料,若有那就去偵測是否有新的版本,否則就去下載。這個類別還做了一件事就是將圖資進行渲染(為了讓圖資檔案比較小,所以使用了向量圖的儲存方式)並喂給MapView去做顯示。


程式碼Code


package lien.ching.maptracker.api;

import android.app.Activity;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import org.mapsforge.map.android.graphics.AndroidGraphicFactory;
import org.mapsforge.map.android.util.AndroidUtil;
import org.mapsforge.map.android.view.MapView;
import org.mapsforge.map.layer.cache.TileCache;
import org.mapsforge.map.layer.labels.LabelLayer;
import org.mapsforge.map.layer.renderer.TileRendererLayer;
import org.mapsforge.map.reader.MapFile;
import org.mapsforge.map.rendertheme.InternalRenderTheme;

import java.io.File;
import java.util.concurrent.TimeUnit;

import lien.ching.maptracker.Constant;
import lien.ching.maptracker.R;
import lien.ching.maptracker.overlay.NowLocationLayout;

/**
 * Created by lienching on 11/27/15.
 * This class is use for checking if the device have the required map file or not.
 */
public class EnvCheck {
    private Context context;
    private String externalpath = Environment.getExternalStorageDirectory().getPath();
    private MapDownloadManager mapDownloadManager;
    private MapUpdateManager mapUpdateManager;
    private mapDownloadManager downloadManger;
    private Activity activity;
    private MapView mapView;
    private NowLocationLayout locationLayout;
    public EnvCheck(MapView mapView,NowLocationLayout locationLayout,Context context,Activity activity){
        this.activity = activity;
        this.context = context;
        this.mapView = mapView;
        this.locationLayout = locationLayout;
    }
    public EnvCheck(Context context,Activity activity){
        this.activity = activity;
        this.context = context;
        this.mapView = null;
    }

    public void CheckAndDownload(String continent, String sourcefile) {
        String mapfile = continent+"/"+sourcefile;
        if(!this.isMapResourceExist(mapfile)) {
            downloadManger = new mapDownloadManager(mapView,locationLayout, context, mapfile);
            Thread thread = new Thread(downloadManger);
            thread.run();
        }
        else{
            MapFile targetFile = new MapFile(new File(Constant.PATH_MAPSFORGE+mapfile));
            TileCache tileCache = AndroidUtil.createTileCache(context, "mapcache", mapView.getModel().displayModel.getTileSize(), 1f, mapView.getModel().frameBufferModel.getOverdrawFactor());
            TileRendererLayer tileRendererLayer = AndroidUtil.createTileRendererLayer(tileCache,mapView.getModel().mapViewPosition,targetFile, InternalRenderTheme.OSMARENDER,true,true);
            tileRendererLayer.setXmlRenderTheme(InternalRenderTheme.OSMARENDER);
            mapView.getLayerManager().getLayers().add(tileRendererLayer);
        }
    }


    public boolean isMapResourceDirExist(final String continent){
        File dir = new File(Constant.PATH_MAPSFORGE+continent);
        if(!dir.exists()) {
            if (!dir.mkdirs()) {
                Log.e("EnvCheck","Dir create failed");
                return false;
            }
            Log.d("EnvCheck","Dir Create Sucess!");
        }
        return true;
    }
    public boolean isMapResourceExist(final String mapfile){
        if(!(new File(externalpath+"/mapsforge").exists()))
            createDirectory();
        File searchFile = new File(externalpath+"/mapsforge/maps/"+mapfile);
        if(searchFile.exists())
            return true;
        return false;
    }

    public void createDirectory(){
        File target = new File(externalpath+"/mapsforge/maps");
        target.mkdirs();
        if(target.exists()&&target.isDirectory()){
            Toast.makeText(context, R.string.toast_dir_success, Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(context, R.string.toast_dir_fail_retry,Toast.LENGTH_SHORT).show();
            target.mkdir();
            if(target.exists()&&target.isDirectory()){
                Toast.makeText(context, R.string.toast_dir_success, Toast.LENGTH_SHORT).show();
            }
            else{
                Toast.makeText(context, R.string.toast_dir_fail, Toast.LENGTH_SHORT).show();
            }
        }
    }
}


說明Explanation


第64行:建立圖資渲染暫存區,For Detail 第65~66行: 建立圖資圖層並設定地圖風格

Step By Step 簡易Mapsforge App開發:NowLocationLayout


目標Achievements


這個類別顧名思義就是要去顯示目前使用者的地理位置並顯示在我們的地圖上面。


程式碼Code


package lien.ching.maptracker.overlay;

import android.Manifest;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.TextView;

import org.mapsforge.core.graphics.Bitmap;
import org.mapsforge.core.graphics.Canvas;
import org.mapsforge.core.graphics.GraphicFactory;
import org.mapsforge.core.graphics.Paint;
import org.mapsforge.core.graphics.Style;
import org.mapsforge.core.model.BoundingBox;
import org.mapsforge.core.model.LatLong;
import org.mapsforge.core.model.Point;
import org.mapsforge.map.android.graphics.AndroidGraphicFactory;
import org.mapsforge.map.android.view.MapView;
import org.mapsforge.map.layer.Layer;
import org.mapsforge.map.layer.overlay.Circle;
import org.mapsforge.map.layer.overlay.Marker;
import org.mapsforge.map.layer.overlay.Polyline;
import org.mapsforge.map.model.MapViewPosition;
import org.mapsforge.map.android.util.AndroidSupportUtil;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import lien.ching.maptracker.R;

/**
 * Created by lienching on 12/2/15.
 */


//This class is using LocationManager to provided location information it may cause some issue, for more reliable location information use  Google Play services location APIs(http://developer.android.com/training/location/index.html)

public class NowLocationLayout extends Layer implements LocationListener,GpsStatus.Listener,ActivityCompat.OnRequestPermissionsResultCallback {


    private Activity activity;
    private MapViewPosition mapViewPosition;
    private MapView mapView;
    private LocationManager locationManager;
    private List history_path;

    private Boolean track;

    //For drawing purpose (http://mapsforge.org/docs/0.6.0/org/mapsforge/map/android/graphics/AndroidGraphicFactory.html)
    private static final GraphicFactory GRAPHIC_FACTORY = AndroidGraphicFactory.INSTANCE;
    private Circle accuray_circle;
    private Marker loc_marker;
    private Polyline usr_path;




    //Constructor
    public NowLocationLayout(Activity activity,MapViewPosition mapViewPosition,MapView mapView){
        this.activity = activity;
        this.mapViewPosition = mapViewPosition;
        this.mapView = mapView;
        this.locationManager = (LocationManager) activity.getSystemService(activity.LOCATION_SERVICE);

        track = false;

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,0, this);
        //Check if location services available
        if(!locationManager.isProviderEnabled (LocationManager.GPS_PROVIDER)){
            activity.startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
        }

        locationManager.addGpsStatusListener(this);//To add satellite listener


        //setDisplayModel(this.displayModel) set circle, polyline, marker etc... in to mapview's display model, so DisplayModel.getTileSize() won't point to a null object.
        accuray_circle = new Circle(null,0,getDefaultCircleFill(),getDefaultCircleStroke());//Circle(LatLong,radius,color,stroke);
        accuray_circle.setDisplayModel(mapView.getModel().displayModel);

        usr_path = new Polyline(getDefaultPolylineStroke(),GRAPHIC_FACTORY);
        usr_path.setDisplayModel(mapView.getModel().displayModel);

        //AndroidGraphicFactory.convertToBitmap() for detail please check AndroidGraphicFactory
        Drawable drawable = activity.getResources().getDrawable(R.drawable.locationmarker);
        Bitmap bitmap = AndroidGraphicFactory.convertToBitmap(drawable);
        loc_marker = new Marker(null, bitmap, 1, 0);
        loc_marker.setDisplayModel(mapView.getModel().displayModel);

        history_path = new LinkedList();//record user path
    }

    //Transfer Function

    private LatLong LocationToLatLong(Location location){
        LatLong latlong = new LatLong(location.getLatitude(),location.getLongitude());
        return latlong;
    }

    //Getter
    protected Paint getPaint(int color, float strokeWidth, Style style){
        Paint paint = GRAPHIC_FACTORY.createPaint();
        paint.setColor(color);
        paint.setStrokeWidth(strokeWidth);
        paint.setStyle(style);
        return paint;
    }

    private Paint getDefaultCircleFill() {
        return this.getPaint(GRAPHIC_FACTORY.createColor(48, 0, 0, 255), 0, Style.FILL);
    }

    private Paint getDefaultCircleStroke() {
        return this.getPaint(GRAPHIC_FACTORY.createColor(160, 0, 0, 255), 2, Style.STROKE);
    }

    private Paint getDefaultPolylineStroke() {
        return this.getPaint(GRAPHIC_FACTORY.createColor(160, 0, 255, 0), 20, Style.STROKE);
    }


    //Enable Location Tracking
    public void startTrack(){
        this.track = true;
    }


    @Override
    public void draw(BoundingBox boundingBox, byte zoomLevel, Canvas canvas, Point topLeftPoint) {
        if(track) {
            loc_marker.draw(boundingBox, zoomLevel, canvas, topLeftPoint);
            accuray_circle.draw(boundingBox, zoomLevel, canvas, topLeftPoint);
        }
        List temp = usr_path.getLatLongs(); //To get all the LatLong that had been drew
        temp.removeAll(temp); //Remove all
        temp.addAll(history_path);//To re-add all path
        usr_path.draw(boundingBox, zoomLevel, canvas, topLeftPoint);
    }

    @Override
    public void onGpsStatusChanged(int event) {

    }

    @Override
    public void onLocationChanged(Location location) {

        LatLong latLong = this.LocationToLatLong(location);
        loc_marker.setLatLong(latLong);
        accuray_circle.setLatLong(latLong);
        history_path.add(latLong);

        accuray_circle.setRadius(location.getAccuracy());

        mapViewPosition.setCenter(latLong);
        mapViewPosition.setZoomLevel((byte) 17);
        requestRedraw();

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {}

    @Override
    public void onProviderEnabled(String provider) {
        locationManager.requestLocationUpdates(provider, 1000L, 0, this);
        if(locationManager.GPS_PROVIDER.equals(provider)) {
            track = true;
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
        if(locationManager.GPS_PROVIDER.equals(provider)){
            track = false;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {}

}


說明Explanation


第79行:這行是用來設定GPS更新頻率,參數大概為(地理資訊提供(GPS, Network), 更新時間(單位:毫秒), 更新距離(當距離超過就更新), 接收資訊的Listener),For Detail
第90、93、99行:如果不把那些物件的DisplayModel設定成MapView的,會出現NullPointerException
第145~147行:第145行是Pass by Reference所以我們可以直接用temp去操作,然後我們先把原本的List清空,再把歷史紀錄再放回去
第164行:這句是利用GPS準確度來當作圓的半徑,For Detail

Step By Step 簡易Mapsforge App開發:MapDownloadManager


目標Achievements


這個類別是用來去做圖資下載相關工作,我在範例中是使用第一種,但是為了學習方便我把另外一種也寫出來了


程式碼Code


1. 使用DownloadManager
package lien.ching.maptracker.api;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.util.Log;

import org.mapsforge.map.android.graphics.AndroidGraphicFactory;
import org.mapsforge.map.android.util.AndroidUtil;
import org.mapsforge.map.android.view.MapView;
import org.mapsforge.map.datastore.MapDataStore;
import org.mapsforge.map.layer.Layer;
import org.mapsforge.map.layer.LayerManager;
import org.mapsforge.map.layer.Layers;
import org.mapsforge.map.layer.cache.TileCache;
import org.mapsforge.map.layer.labels.LabelLayer;
import org.mapsforge.map.layer.renderer.TileRendererLayer;
import org.mapsforge.map.reader.MapFile;
import org.mapsforge.map.rendertheme.InternalRenderTheme;

import java.io.File;
import java.net.URL;

import lien.ching.maptracker.Constant;
import lien.ching.maptracker.overlay.NowLocationLayout;


/**
 * Created by lienching on 12/21/15.
 */
public class mapDownloadManager implements  Runnable{


    private DownloadManager downloadManager;
    private Context context;
    private Long enqueue;
    public MapView mapview;
    public String target;
    private BroadcastReceiver receiver;
    private NowLocationLayout locationLayout;
    public mapDownloadManager(MapView mapView,NowLocationLayout locationLayout,Context context, final String target){
        super();
        this.context = context;
        this.target = target;
        this.mapview = mapView;
        this.locationLayout = locationLayout;
    }
    @Override
    public void run() {
        downloadManager = (DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://download.mapsforge.org/maps/" + target));
        request.setDestinationInExternalPublicDir("mapsforge/maps/",target);
        enqueue = downloadManager.enqueue(request); //Active Download Process
        receiver = new LayerAdder(mapview,locationLayout,target,enqueue); //Created exclusive receiver
        context.registerReceiver(receiver,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); //Registered Reciever
    }


}


2. 使用HTTP Download (Async)
package lien.ching.maptracker.api;

import android.app.Activity;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import lien.ching.maptracker.Constant;
import lien.ching.maptracker.MainActivity;

/**
 * Created by lienching on 11/27/15.
 * In this class, I want to put downloading process in to Async
 * I directly implementing the HTTP Download in doInBackground()
 * In the app I didn't use this class as the download class
 * if you want to see the source code that use in the app
 * please check mapDownloadManager.class for more detail
 */
public class MapDownloadManager extends AsyncTask{
    private Context context;
    private Activity activity;
    private ProgressDialog dialog;
    public PowerManager.WakeLock wakeLock;
    public MapDownloadManager(Context context,Activity activity){
        super();
        this.activity = activity;
        this.context = context;
    }

    @Override
    protected Boolean doInBackground(String... params) {

        //For Details, please check http://stackoverflow.com/a/3028660
        String continent = params[1];
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        File outputFile = new File(Constant.PATH_MAPSFORGE+params[0]);

        try{
            URL url = new URL("http://download.mapsforge.org/maps/"+params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            if(connection.getResponseCode() != HttpURLConnection.HTTP_OK){
                Toast.makeText(context,"Connection Fail..."+connection.getResponseCode(),Toast.LENGTH_SHORT).show();
                return false;
            }
            input = connection.getInputStream();
            if(outputFile.exists()){
                output = new FileOutputStream(outputFile);
            }
            else{
                EnvCheck envCheck = new EnvCheck(context,activity);
                envCheck.isMapResourceDirExist(continent);
                outputFile.createNewFile();
                output = new FileOutputStream(outputFile);

            }

            byte data[] = new byte[8192];
            int count;
            long total = 0;
            while((count = input.read(data)) != -1){
                if(isCancelled()) {
                    input.close();
                    return false;
                }
                total += count;
                output.write(data,0,count);
            }

            Log.d("MapDownloadManager","Write "+total+" bytes");
        }catch (Exception e){
            Log.e("MapDownloadManager","Writing Data:"+e.toString());
            return false;
        }finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }
            outputFile.setLastModified(connection.getLastModified());
            if (connection != null)
                connection.disconnect();
        }
        return false;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        PowerManager pm = (PowerManager) activity.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, activity.getClass().getName());
        wakeLock.acquire();
        dialog = new ProgressDialog(activity);
        dialog.setMessage("Map Source Downing");
        dialog.setCancelable(false);
        dialog.setIndeterminate(true);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.show();
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        if(dialog.isShowing()){
            dialog.dismiss();
        }
        if(wakeLock.isHeld())
            wakeLock.release();
        try {
            if (!aBoolean)
                Toast.makeText(context, "Download error", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
        }
        catch (Exception e){
            Log.d("MapUpdateManager", e.toString());
        }
    }
}


說明Explanation


第一種方式非常的單純也比較不需要擔心使用者不小心離開程式的時候會發生問題,但是缺點就是需要用Reciever去做下載完成判斷
第二種就是比較資工系的做法,直接實作HTTP Download,這個方法的好處就是可以對於"下載"這個動作做很多客製化的事情,但是要處理的事情就很多

Step By Step 簡易Mapsforge App開發:LayerAdder


目標Achievements


這個類別目的是要用來做動態新增圖層


程式碼Code


package lien.ching.maptracker.api;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import org.mapsforge.map.android.graphics.AndroidGraphicFactory;
import org.mapsforge.map.android.util.AndroidUtil;
import org.mapsforge.map.android.view.MapView;
import org.mapsforge.map.layer.cache.TileCache;
import org.mapsforge.map.layer.labels.LabelLayer;
import org.mapsforge.map.layer.renderer.TileRendererLayer;
import org.mapsforge.map.reader.MapFile;
import org.mapsforge.map.rendertheme.InternalRenderTheme;
import org.mapsforge.map.rendertheme.rule.RenderTheme;

import java.io.File;

import lien.ching.maptracker.Constant;
import lien.ching.maptracker.overlay.NowLocationLayout;

/**
 * Created by lienching on 1/7/16.
 */

//http://developer.android.com/reference/android/content/BroadcastReceiver.html
public class LayerAdder extends BroadcastReceiver {
    private MapView mapView;
    private String target;
    private NowLocationLayout locationLayout;
    private Long enqueue;
    public LayerAdder(MapView mapView,NowLocationLayout locationLayout,String target,Long enqueue){
        super();
        this.mapView = mapView;
        this.target = target;
        this.enqueue = enqueue;
        this.locationLayout = locationLayout;
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
            long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
            if(downloadId == enqueue){
                MapFile targetFile = new MapFile(new File(Constant.PATH_MAPSFORGE+target));
                TileCache tileCache = AndroidUtil.createTileCache(context, "mapcache", mapView.getModel().displayModel.getTileSize(), 1f, mapView.getModel().frameBufferModel.getOverdrawFactor());
                TileRendererLayer tileRendererLayer = AndroidUtil.createTileRendererLayer(tileCache,mapView.getModel().mapViewPosition,targetFile, InternalRenderTheme.OSMARENDER,true,true);
                tileRendererLayer.setXmlRenderTheme(InternalRenderTheme.OSMARENDER);
                mapView.getLayerManager().getLayers().add(tileRendererLayer);
                mapView.getLayerManager().getLayers().remove(locationLayout);//LocationLayout need be the top layout of the mapview, to keep user location visible
                mapView.getLayerManager().getLayers().add(locationLayout);
                Log.d("LayerAdder",target+" Download Completed"+", LayerAdd");
            }
        }
    }
}
 

說明Explanation


BroadcastReceiver是我用來去偵測檔案是否下載完成的類別

2016年2月19日 星期五

Step By Step 簡易Mapsforge App開發:MainActivity


目標Achievements


這個Class是我們App的導入點,我稱這種類別為Main類別,那我們在這個類別中我們就需要去做整個程式大方向的規劃.

程式碼Code


package lien.ching.maptracker;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;

import org.mapsforge.core.model.LatLong;
import org.mapsforge.core.model.MapPosition;
import org.mapsforge.map.android.graphics.AndroidGraphicFactory;
import org.mapsforge.map.android.util.AndroidUtil;
import org.mapsforge.map.android.view.MapView;
import org.mapsforge.map.datastore.MapDataStore;
import org.mapsforge.map.datastore.MultiMapDataStore;
import org.mapsforge.map.layer.cache.TileCache;
import org.mapsforge.map.layer.renderer.TileRendererLayer;
import org.mapsforge.map.reader.MapFile;
import org.mapsforge.map.rendertheme.InternalRenderTheme;

import java.io.File;

import lien.ching.maptracker.api.EnvCheck;
import lien.ching.maptracker.overlay.NowLocationLayout;

/**
 * Created by lienching on 11/27/15.
 */
public class MainActivity extends Activity {
    private MapView mapView;
    private MapDataStore taiwanMap,worldMap;
    private MultiMapDataStore multiMapDataStore;
    private TileCache tileCache;
    private TileRendererLayer tileRendererLayer;
    private EnvCheck envCheck;
    private NowLocationLayout nowLocationLayout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AndroidGraphicFactory.createInstance(this.getApplication()); //Initiation Mapsforge Library
        mapView = new MapView(this);
        mapView.setClickable(true);
        mapView.getMapScaleBar().setVisible(true);
        mapView.setBuiltInZoomControls(true);
        mapView.getMapZoomControls().setZoomLevelMin((byte) 5);
        mapView.getMapZoomControls().setZoomLevelMax((byte) 20);
        mapView.getModel().mapViewPosition.setMapPosition(new MapPosition(new LatLong(23.6, 121), (byte) 7));
        //Disable hardware acceleration at mapview, for more detail about this line of code please check (https://goo.gl/v5weg9)
        mapView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        setContentView(mapView);
        nowLocationLayout = new NowLocationLayout(this,mapView.getModel().mapViewPosition,mapView);
        envCheck = new EnvCheck(mapView,nowLocationLayout,this.getApplicationContext(),this);
        //To keep screen on(http://developer.android.com/training/scheduling/wakelock.html)
        this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    }

    @Override
    protected void onStart() {
        super.onStart();

        envCheck.CheckAndDownload("world", "world-lowres-0-7.map"); //Check if the map source exist
        envCheck.CheckAndDownload("asia", "taiwan.map");
        mapView.getLayerManager().getLayers().add(nowLocationLayout);//Add Location Layer
        nowLocationLayout.startTrack();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        this.mapView.destroyAll();
    }

}


說明Explanation


第41行:這一行因為Mapsforge所用的androidsvg必須要做一些初始化,所以我們在第一行就將他呼叫避免後續問題
第50行:用來關閉硬體加速( For Detail
) 第55行:因為這個範例是要用來紀錄使用者的移動軌跡,所以需要使用這行(For Detail)
第63~64行:檢查檔案是否存在或有沒有新版本,(詳細運作請參考EnvCheck)
第65~66行:因為前兩行需要花時間但也必須要讓使用者知道程式有在運作,所以先讓定位開始運作

2016年2月5日 星期五

Step By Step 簡易Mapsforge App開發:Introduction


前言


先前筆者有稍微介紹了Mapsforge,不知道大家目前有沒對於Mapsforge產生了一點興趣呢? 這次筆者打算用一個比較不抽象的方式來教大家Mapsforge要如何使用~ 本次專案的程式碼將會發佈在 https://github.com/lienching/MapTracker

前置準備Preparation


  1. 使用者所需具備能力
    1. 基本的Java概念
    2. 基本的Android APP開發概念
    3. 熱愛開發的心
  2. 專案所需API(mapsforge系列載點、androidsvg載點、kXML2載點)
    1. mapsforge-map
    2. mapsforge-core
    3. mapsforge-map-android
    4. mapsforge-map-reader
    5. androidsvg
    6. kXML2


AndroidManifest設置Setup


權限部分(詳細請參考這裡)
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>

這個教學將會有6個部分,分別為 然後他們有一個共用的常數庫 Constant.java
package lien.ching.maptracker;

import android.os.Environment;

/**
 * Created by lienching on 11/27/15.
 */
public class Constant {
    public static final String PATH_MAPSFORGE = Environment.getExternalStorageDirectory().toString() + "/mapsforge/maps/";
    public static final String PATH_WORLDMAP = PATH_MAPSFORGE + "world/world-lowres-0-7.map";
    public static final String PATH_TAIWANMAP = PATH_MAPSFORGE + "asia/taiwan.map";

}

2015年11月3日 星期二

Mapsforge:Get Started


前置準備Preparation


Mapsforge是一個很棒的Vector Map Library,相信讀者一定很想要趕快著手開發 但在開始前需要先準備好一些東西

API部分

  • mapsforge-core: 這是Mapsforge的核心Library所有相關Mapsforge的Library都是以他為基礎
  • mapsforge-map: 這個是負責Mapsforge中地圖相關處裡的Library
  • mapsforge-map-android: 這個Library中提供了一些如MapView, AndroidGraphicFactory等讓Android可以充分使用Mapsforge的物件
  • mapsforge-map-reader: 這個Mapsforge的.map檔的解析器Library
以上可以在 Mapsforge專案 中找到

圖資部分

這個範例是離線地圖,所以首先你需要2個圖資
  • 1. world-lowres-0-7.map
  • 2. taiwan.map
以上兩個檔案須放在外部儲存空間中的mapsforge/maps/(所屬的洲)裡 所以如果兩個檔案的完整路徑則為
  • 1. mapsforge/maps/world/world-lowres-0-7.map
  • 2. mapsforge/maps/asia/taiwan.map

範例程式Sample

(本範例所使用的Mapsforge版本為0.6.0-rc1)




SampleMapView.java
import android.app.Activity;
import android.os.Bundle;

import org.mapsforge.core.model.LatLong;
import org.mapsforge.core.model.MapPosition;
import org.mapsforge.map.android.graphics.AndroidGraphicFactory;
import org.mapsforge.map.android.util.AndroidUtil;
import org.mapsforge.map.android.view.MapView;
import org.mapsforge.map.datastore.MapDataStore;
import org.mapsforge.map.datastore.MultiMapDataStore;
import org.mapsforge.map.layer.cache.TileCache;
import org.mapsforge.map.layer.renderer.TileRendererLayer;
import org.mapsforge.map.reader.MapFile;
import org.mapsforge.map.rendertheme.InternalRenderTheme;

import java.io.File;

/**
 * Created by lienching on 10/17/15.
 */
public class SimpleMapView extends Activity {

    private MapView mapView;
    private MultiMapDataStore multiMapDataStore;
    private MapDataStore worldMap,taiwanMap;
    private TileCache tileCache;
    private TileRendererLayer tileRendererLayer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AndroidGraphicFactory.createInstance(this.getApplication());//使用Mapsforge Library必須呼叫此方法來初始化
        mapView = new MapView(this);
        mapView.setClickable(true);
        mapView.getMapScaleBar().setVisible(true);
        mapView.setBuiltInZoomControls(true);
        mapView.getMapZoomControls().setZoomLevelMin((byte) 5);
        mapView.getMapZoomControls().setZoomLevelMax((byte) 20);

        worldMap = new MapFile(new File(Constant.PATH_WORLDMAP));
        taiwanMap = new MapFile(new File(Constant.PATH_TAIWANMAP));
        multiMapDataStore = new MultiMapDataStore(MultiMapDataStore.DataPolicy.RETURN_ALL);

        tileCache = AndroidUtil.createTileCache(this, "mapcache", mapView.getModel().displayModel.getTileSize(), 1f, this.mapView.getModel().frameBufferModel.getOverdrawFactor());
        setContentView(mapView);
    }

    @Override
    protected void onStart() {
        super.onStart();
        multiMapDataStore.addMapDataStore(worldMap,true,true);
        multiMapDataStore.addMapDataStore(taiwanMap,false,false);
        //multiMapDataStore.setStartPosition(new LatLong(23, 121));
        //multiMapDataStore.setStartZoomLevel((byte) 7);
        tileRendererLayer = new TileRendererLayer(tileCache,multiMapDataStore,mapView.getModel().mapViewPosition,false,true, AndroidGraphicFactory.INSTANCE);
        tileRendererLayer.setXmlRenderTheme(InternalRenderTheme.OSMARENDER);

        mapView.getModel().mapViewPosition.setMapPosition(new MapPosition(new LatLong(23, 121), (byte) 7));
        mapView.getLayerManager().getLayers().add(tileRendererLayer);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.mapView.destroyAll();
    }
}

Constant.java
import android.os.Environment;

/**
 * Created by lienching on 10/19/15.
 */
public class Constant {
    private static final String PATH_MAPSFORGE = Environment.getExternalStorageDirectory().toString() + "/mapsforge/maps/";
    public static final String PATH_WORLDMAP = PATH_MAPSFORGE + "world/world-lowres-0-7.map";
    public static final String PATH_TAIWANMAP = PATH_MAPSFORGE + "asia/taiwan.map";

}


Q&A


1. 如果我很懶,我有甚麼辦法可以讓App自己下載圖資呢?

那妳可以建立一個專門下載圖資的類別,範例如下
import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Environment;


/**
 * Created by lienching on 10/14/15.
 * The purpose of this class is to define the map resource download methods, so we
 * can easily download a map resource by this class.
 */
public class MapDownloadManager{
    private DownloadManager downloadManager;
    private DownloadManager.Request request;
    private String external_path = Environment.getExternalStorageDirectory().toString();
    private Context context;
    public MapDownloadManager(Context context){
        this.context = context;
        downloadManager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);

    }
    public void downloadMapResource(String mapfile){
        Uri download_URI = Uri.parse("http://download.mapsforge.org/maps/"+mapfile);
        request = new DownloadManager.Request(download_URI);
        //Set the network type which is allow to process the download request
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        //Set whether this download may proceed over a roaming connection.
        request.setAllowedOverRoaming(false);
        request.setTitle("Mapsforge Map Download");
        request.setDestinationInExternalPublicDir("/mapsforge/maps/",mapfile);
        downloadManager.enqueue(request);
    }
}

之後只要在主類別中呼叫就能使用囉~

2015年10月27日 星期二

Mapsforge: Introduction


前言

    經過筆者跟 OSMDROID 過招多次之後,我發覺它在離線地圖的實現上真的不怎麼理想,而筆者對於向量圖的處理技術並不成熟,所以筆者就決定要搜尋其他Library來取代OSMDROID,也因此找到了Mapsforge這個Library。


Mapsforge簡介

    Mapsforge提供一個免費且開源的離線向量圖函式庫給Android與Java平台,這個函式庫的特色就是可以用簡短的幾行程式碼就能輕易的實現OpenStreetMap相關應用程式的開發。這個函式庫計畫起初是由德國柏林自由大學的資訊科學研究所(Computer Science Institute of Freie Universität Berlin)在2008年發起並開始開發並以LGPL3開源,而目前這個函式庫是由眾多志工一起維護。


為什麼Mapsforge


  • 可以在本機直接渲染OpenStreetMap地圖資料 - 實現離線地圖
  • 強力且具彈性的圖層API - 讓地圖更加豐富
  • 壓縮的圖資檔案格式 - 圖資檔案小離線地圖無負擔
  • 支援多點觸控 - 定義更多手勢實現更多功能
  • 支援多種OSM標籤 - 地圖顯示更細緻展現更多
  • 只要Android版本在2.3以上就能輕易使用 - 讓你的App更多人能用
  • 函式庫檔案小且其中已包含圖片 - App更輕巧
  • API的操作非常簡單還有大量範例可以參考 - 輕鬆入門
  • 100% 免費且是LGPL3開源 - 開發成本DOWN~靈活性Up!!!



開始用Mapsforge開發OSM應用

2015年8月10日 星期一

OSMDROID: Overlay


介紹Introduction


Overlay 可以說是OSMDROID中一個恨重要的一部分,因為這個物件可以讓我們的地圖擁有更多的功能,像是在地圖上加上其他地圖(如鐵軌地圖等),或著是增加判定(如按住時要出現什麼功能)

範例Example


首先我們先建立一個類別,然後將他繼承Overlay 繼承之後他會顯示錯誤,因為必須要在Override
draw(Canvas canvas, MapView mapView, boolean b)
這個method
public class DemoOverlay extends Overlay {
    @Override
    protected void draw(Canvas canvas, MapView mapView, boolean b) {}//繪製地圖
}
當我們Override之後還是會發現,IDE依舊顯示說他錯誤,原因在於Overlay本身沒有預設建構元,所以我們必須針對我們所定義的類別寫一個建構元, 但就如同我前面所寫,Overlay本身沒有預設建構元,那我們就會想問那要怎麼樣才能正確的定義好呢?這時候我們就要來思考Overlay這個類別特性了 Overlay他是一個建立在MapView上面的一層圖層,而MapView是Activity的內容之一,那我們就可以針對這點去查一下API,果然Overlay本身就有一個建構元叫做
public Overlay(Context context)
這時我們的IDE就不會再報錯了,那我們的基本型也就完成了
public class DemoOverlay extends Overlay {
    public DemoOverlay(Context ctx){ //初始建構元,如果沒有這個會報錯誤,因為Overlay本身沒有定義空白建構元
        super(ctx);
    }
    @Override
    protected void draw(Canvas canvas, MapView mapView, boolean b) {} //繪製地圖
}
以下是個小小的範例,這個程式碼是在說當使用者按住螢幕的時候,就會顯示"Long Press"的提示文字
public class DemoOverlay extends Overlay {
    Context ctx;
    public DemoOverlay(Context ctx){ //初始建構元,如果沒有這個會報錯誤,因為Overlay本身沒有定義空白建構元
        super(ctx);
        this.ctx = ctx;
    }
    @Override
    protected void draw(Canvas canvas, MapView mapView, boolean b) { //繪製地圖

    }

    @Override
    public boolean onLongPress(MotionEvent e, MapView mapView) { //判定按住時,要做什麼
        Toast.makeText(ctx,"Long Press",Toast.LENGTH_SHORT);
        return super.onLongPress(e, mapView);
    }
}

那我們現在完成Overlay了,但是你會發現為什麼我們的Overlay沒有作用呢? 那是因為我們還需要把他載入到我們的MapView當中 載入方式非常簡單
DemoOverlay demoOverlay = new DemoOverlay(this);//宣告一個DemoOverlay的物件
mapView.getOverlays().add(demoOverlay);//mapView是你所宣告的MapView物件

mapView加入Overlay有先後順序,所以我建議如果是顯示層的Overlay(如鐵路地圖、標示等)要比判定層的Overlay(如長按增測)還要早加入MapView當中

2015年6月28日 星期日

OSMDROID:TileProvider


介紹Introduction


  TileProvider是在OSMDROID中很重要的一個部分,他負責從Tile Server或記憶卡中將圖資拿出來並喂給MapView去做顯示。

OSMDROID內建的圖資


  在OSMDROID中有支援以下幾種圖資:
OpenStreetMap提供
(1)MAPNIK
OpenCycleMap提供
(2)CYCLEMAP
Open Public Transport Map提供
(3)PUBLIC_TRANSPORT

MapQuest提供
(4)MAPQUESTOSM
(5)MAPQUESTAERIAL
(6)MAPQUESTAERIAL_US

CloudMade提供
(7)CLOUDMADESTANDARDTILES
(8)CLOUDMADESMALLTILES

OpenStreetMap Nederland提供
(9)FIETS_OVERLAY_NL
(10)BASE_OVERLAY_NL
(11)ROADS_OVERLAY_NL

以上圖資使用方式(以MAPNIK為例)
mapview.setTileSource(TileSourceFactory.MAPNIK);

自訂TileSource


看不慣內建的TileSource嗎?一定在想說可不可以更換對吧答案是可以的喔~,只要這樣寫就好了(以CartoDB Light為例,更多TileSource可以去OpenStreetMap的Wiki查看)
public static final OnlineTileSourceBase CARTODB = new XYTileSource("CartoDB", ResourceProxy.string.unknown,2,19,256,".png",new String[]{
            "http://a.basemaps.cartocdn.com/light_all/"});
先來說一下XYTileSource的參數說明
XYTileSource("Tile的名稱", Tile的ID(如果在ResourceProxy中沒有定義直接用unknown就好), Tile最小的zoom level, Tile最大的zoom level, Tile的圖資大小(256x256就寫256,如果是512x512就寫512), "Tile圖資的副檔名(如果是png就寫 .png)", 圖資的網址或位置(如果有多個位置可以用String[]來定義多個位置) );
這樣宣告完就能設定MapView的圖資是我們自己自訂的囉~
mapview.setTileSource(CARTODB);

2015年5月22日 星期五

OSMDROID: MapController


介紹Introduction


  MapController拆開來是 Map Controller但是雖然說是Controller但是能控制的真的還蠻有限的...當然這個類別只是讓一些操作比較容易一點,所以如果你想直接操作MapView的話也是可以。在MapController中主要就是在設定啟動時的Map Center與設定Map的Zoom Level,還有就是縮放特效的調整。

方法介紹Method Introduction


設定螢幕正中央的經緯度
GeoPoint startPoint = new GeoPoint(latitude, longitude);//GeoPoint(緯度y,經度x)
mapController.setCenter(startPoint);
地圖Zoom Level設定(通常值是介於1~18,這取決於圖資所能提供的Zoom Level來決定,值越大就越多細節)
mapController.setZoom(12); //將Zoom Level設定在12
縮放動畫設定
mapController.stopAnimation(true);//停止動畫效果
mapController.stopAnimation(false);//開啟動畫效果

2015年5月10日 星期日

OSMDROID:MapView


簡介


  OpenStreetMap最核心的部分,就是他的地圖囉,而在OSMDROID中當然也會有個東西用來顯示地圖的元件,那就是我們現在要來介紹的MapView
OSMDROID的MapView是改寫Android本身的MapView,簡單來說就是把原本是Google Map的MapView變成是OpenStreetMap的。

使用方式


OSMDROID中用MapView有兩種方式,一種是寫在Layout裡面,一種是寫在Activity裡面 首先先介紹如果寫在Layout裡面會是什麼樣子
<org.osmdroid.views.MapView
        android:id="@+id/mapview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tilesource="Mapnik"
        />

然後是Activity中的寫法
public class MainActivity extends Activity {
    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        MapView map = (MapView) findViewById(R.id.map);
        map.setTileSource(TileSourceFactory.MAPNIK);
    }
}

這兩種寫法都很棒,就看個人習慣囉

另外MapView還有提供一些其他的方法,像是
這是在MapView上新增內建的縮放工具
map.setBuiltInZoomControls(true);

這個是啟用兩指縮放功能
map.setMultiTouchControls(true);

這是限制最大縮放等級
map.setMaxZoomLevel(16);
這是限制最小縮放等級
map.setMinZoomLevel(1);
這個是在設定說是否當本機沒有圖資時,允許讓MapView去跟Tile Server要圖資
map.useDataConnection(true);
最後這個是個很重要的東西,因為Android能支援的螢幕解析度太多了,但圖資的解析度是固定的,所以可能會出現到明明Zoom Level已經到最細緻的部分了,但還是沒辦法看到全部的東西,所以OSMDROID中提供這個方法可以根據手機的螢幕解析度去將圖資做一些調整,讓圖資顯示正常。
map.setTilesScaledToDpi(true);

2015年5月6日 星期三

OSMDROID: Introduction



簡介  Introduction

OSMDROID是一個Android的函式庫,主要目的是要提供與OpenStreetMap(簡稱OSM)互動的工具,裡面包含了:


MapView:

    提供一個類似Android中MapView的環境,讓OSM的圖資可以顯示在Android中,並可以做拖拉,縮放,圖資來源設定等動作。
MapController:

    這是個設定工具,也就是對於MapView的Zoom Level與起始位置做設定。
TileProvider:

    TileProvider主要是負責MapView圖資的部分,OSMDROID本身的MapView是需要給他一個圖資來源才能運作的,而提供圖資這個部分就是TileProvider的工作。
Overlay:

    Overlay照字面上就是圖層,在OSMDROID中底層是MapView,但如果我們需要去新增一些事件, 要繪製矩形區域, 放置指標等行為就會需要去新增一個圖層定義其行為模式。



安裝  Install

  1. 使用Android Studio

    Android Studio真的是個很棒的工具,因為在安裝Library上面真的非常的方便,像OSMDROID你只需要在專案中建立一個libs的資料夾,然後把osmdroid的jar檔跟slf4j-android(載點)放進去就可以囉
    p.s 如果你發現你放進去了但是卻不能使用的話,請檢查一下專案中的build.gradle中的dependencies大括號裡面有沒有 compile fileTree(dir: 'libs', include: ['*.jar']) 這行,如果沒有補上去之後Sync就會正常了。
  2. 使用Maven

    把
    <dependency>
      <groupid>org.osmdroid</groupid>
      <artifactid>osmdroid-android</artifactid>
      <version>4.3</version>
    </dependency>
    

    跟
    <dependency>
        <groupid>org.slf4j</groupid>
        <artifactid>slf4j-android</artifactid>
        <version>1.6.1-RC1</version> 
    </dependency>
    

    放進Maven設定檔中就可以囉。
  3. 使用Eclipse

    把OSMDROID的Jar檔跟slf4j-android(載點)下載好,之後
    對著專案點右鍵 內容(Properties) > Java Build Path > Add External JARs > 選擇剛下載的OSMDROID跟slf4j-android > 確定 這樣就完成囉。
最後記得別忘了在AndroidManifest.xml中把這幾行權限加進去喔
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


下載  Download


    你們可以從(網址)取得最新版本(OSMDROID在Google Code上面也有上傳相關的檔案,但是版本到4.2就停止更新了)
當你進去的時候你會發現有三種不同的檔名,分別是:

  1. osmdroid-android-x.x-javadoc.jar

        這個裡面存放的是OSMDROID這個版本中的所有API的說明,解壓縮之後裡面會是個網站,點擊index.html之後你就會看到















    這個漂亮的網站囉~
  2. osmdroid-android-x.x-sources.jar

        這個檔案中存放的就是完整OSMDROID的原始碼,也就是可以讓你離線也能查閱原始碼喔,當然如果你喜歡線上版的你也可以參閱他們Github的專案
  3. osmdroid-android-x.x.jar

        這個就是我們要放在我們專案中的jar檔囉,裡面放了全部OSMDROID編譯過的檔案,讓我們可以在我們的程式中使用。

2015年4月30日 星期四

2015/04/30 OSMDFE開發日誌(二)

最近在準備期中考比較忙一點
就有點忘記更新了...
有點糟糕
先來Po目前的進度截圖~
 先大致說明一下
我底圖是用MapNIK做為圖資來源
藍色發光點代表的是使用者目前的所在位置
如果使用者按住底圖的某個點
就會出現綠色的標籤
那個代表使用者要新增的地點
然後PopWindows中有三個按鈕
Save:將資料寫入儲存空間&伺服器
Reset:將去伺服器取得前一個版本的內容並顯示出來
Delete:刪除目前這個新增標籤
以上前端的部分

至於後端的部分
我已經大致把與伺服器連接的相關方法已經都定義出來了
目前有這兩種型態的postData
postData(String ip, JSONObject json,Context context)//這個用來傳送使用者所新增的點
postData(String ip,Double latitude, Double longitude,Context context) //這個用來取得使用者周邊的點
至於REST API的部分撰寫正在進行中,就會全面轉換成用RestAPI做溝通
應該近期內就會完成

再來就是伺服器的部分
上次討論結果大致架構如下
1.App與資料庫資料
App <----REST API---->資料庫
2.網頁呈現方式
Umap <----REST API---->資料庫
3.OpenData
客戶端 ----REST API---->資料庫
客戶端<----轉為Json格式----資料庫
資料庫部分目前我也還在規劃當中
近期也會開始進行開發的部分

最後要來講一下目前的一些小小問題
目前正在研究我該怎麼在PopWindow中直接操作到MapView
因為我要讓Delete可以運作啊!!

心情抒發時間~
案子開發到現在...覺得自己進度有點...不對是非常緩慢,至於為什麼呢~大概就是不知道為什麼,教授都喜歡在期中前開始塞一大堆東西給我們,雖然也見怪不怪了但是每次做完就累癱了,真的開發時間就縮短很多... 我真的不是故意的...OAQ。Whatever, 期中考完之後會有段輕鬆期,要好好在這個時期把進度趕回來(握拳) 。

2015年3月26日 星期四

2015/03/27 OSMDFE開發日誌(一)

OSMDFE計畫也執行了一段時間,程式架構一改再改也終於訂出一個還算滿意的架構,算是蠻值得慶幸的事~ 所以也已經可以正式Coding啦,目前整個計畫我執行到地圖正常顯示且也已經能將使用者的位置標示在地圖上(如果抓不到的話就顯示整個台灣),雖然還是有些小Bug存在但也找到一些解決方案所以不算有太大的阻礙。既然這是開發日誌還是要放一些我遇到的問題與解決方案囉。
1.首先我遇到的問題就是在OSMDROID中Mapcontroller.setCenter()這個的offset問題,這個問題算折騰我還蠻久的,但還是解決啦~
 解決方案:將OSMDROID的版本從4.2更新至4.3

2.接下來我遇到的就是TileSource的問題,TileSource這個算是兩個問題

 (1) Zoom Level調到18(最高)卻只有相較於OpenStreetMap官網的Zoom Level 17的效果
 解決方案:使用 mapview.setTilesScaledToDpi(true)來讓TileSource可以吻合螢幕解析度

 (2)離線TileSource的問題
  其實這不算個問題,只是純粹搞不清楚OSMDROID背後在做什麼而已,舊版的OSMDROID4.2他會一直從伺服器抓資料下來,但到了4.3他就會去自動偵測SD卡中有沒有相對應的Tile,如果有就直接建構就不去伺服器拉資料,真的聰明很多。

3. Marker 問題
 解決方案:原本OSMDROID內建的Marker不是很好用,但我在網路上找到一個算擴充包的API叫做 OSMBONUSPACK ,他裡面提供的Marker就非常的易於使用(p.s 因為Google Code要關閉了,而OSMBONUSPACK本來就是託管在Google Code上面所以我就把它的程式碼拉到我的Github了)
 參考網址:Google Code:https://code.google.com/p/osmbonuspack/
        我轉移到我Github:https://github.com/lienching/osmbonuspack


目前一些基本問題都已經有起色了,我最後來說一下我目前使用了哪些API並他們的功用吧
  • OSMDROID_4.3 : 提供MapView、MapController等與OSM互動的工具
  • OSMBONUSPACK : 提供一些OSMDROID中沒有的工具或寫得比OSMDROID更好的工具
  • geojson : 這是用來解析與製作geojson的api, 我們目前是打算使用geojson來作為資料交換的格式