android studio高德地圖的顯示於定位(附帶逆地理編碼圍欄)

来源:http://www.cnblogs.com/LiangPF/archive/2017/06/02/6932501.html
-Advertisement-
Play Games

首先註冊高德成為開發者(打開高德地圖,點擊底部的開發者平臺),創建應用,按照要求填寫相應信息 網站:http://lbs.amap.com/api/android-sdk/guide/create-project/get-key 途中包含了發佈版的SHA1安全碼和測試版SHA1安全碼,兩者的值可以看 ...


 

首先註冊高德成為開發者(打開高德地圖,點擊底部的開發者平臺),創建應用,按照要求填寫相應信息

網站:http://lbs.amap.com/api/android-sdk/guide/create-project/get-key        

途中包含了發佈版的SHA1安全碼和測試版SHA1安全碼,兩者的值可以看  

照做就一定會獲取的。

 

這裡我講發佈版和調試版都用的relase版本的sha1

 

之後再去下載相應的Jar包,這裡我用的是

3D地圖的jar包

 

註意:2D地圖的jar包,與3D地圖的jar包因為介面有一樣的,導致衝突無法使用。

 

在jnilibs下放入一下文件

 

因為有些人的android studio無法顯示,但又不報錯(我就這樣)。你就需要將以上紅圈類容放入libs,才能顯示

 

之後在

將導入的jar包添加到類包;

 

 

選擇,找到於自己名字一樣的Jar,添加就可以了。之後檢查在build.gradle 是否添加了以下類容

compile files('libs/AMap3DMap_5.1.0_AMapSearch_5.1.0_AMapLocation_3.4.0_20170518.jar')
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'

 

並且設置jar包的位置為libs

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

 

在androidManifest.xml中添加自己的添加許可權

<!-- 用於進行網路定位 -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <!-- 用於訪問GPS定位 -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <!-- 用於獲取運營商信息,用於支持提供運營商信息相關的介面 -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!-- 用於訪問wifi網路信息,wifi信息會用於進行網路定位 -->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <!-- 用於獲取wifi的獲取許可權,wifi信息會用來進行網路定位 -->
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <!-- 用於訪問網路,網路定位需要上網 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- 用於讀取手機當前的狀態 -->
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <!-- 用於寫入緩存數據到擴展存儲卡 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!-- 用於申請調用A-GPS模塊 -->
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <!-- 用於申請獲取藍牙信息進行室內定位 -->
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

  添加自己的key

<meta-data
                android:name="com.amap.api.v2.apikey"
                android:value="你的key" />

  添加定位方法

<service android:name="com.amap.api.location.APSService" />

  

在Activity_main.xml中添加

<TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/text1"/>
<com.amap.api.maps.MapView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/map">
        </com.amap.api.maps.MapView>

 

 

在MainActivty的主代碼

public class MainActivity extends AppCompatActivity implements AMapLocationListener,GeocodeSearch.OnGeocodeSearchListener {

    private Button button;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private TextView textView;
    private String[] strMsg;
    private com.amap.api.maps.AMap aMap;
    private MapView mapView;
    private GeocodeSearch geocoderSearch;
    private Marker geoMarker;
    private static LatLonPoint latLonPoint;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView)findViewById(R.id.text1);
        textView = (TextView)findViewById(R.id.textView2);
        button=(Button)findViewById(R.id.button);
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必須重寫
        Location();
        final Intent intent=new Intent();
        intent.setAction("Utils");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle data =new Bundle();
                data.putString("msg","簽到成功");
                intent.putExtra("data",data);
                sendBroadcast(intent);


            }
        });
    }




    private void initMap(){

        if (aMap == null) {
            aMap = mapView.getMap();

            //用高德預設圖標
            geoMarker= aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
            //自定義圖標
           //geoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
           //   .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.punch_dw))));
        }
        geocoderSearch = new GeocodeSearch(this);
        geocoderSearch.setOnGeocodeSearchListener(this);
        getAddress(latLonPoint);
    }


    @Override
    public void onLocationChanged(AMapLocation loc) {
        if (null != loc) {
            Message msg = mHandler.obtainMessage();
            msg.obj = loc;
            msg.what = Utils.MSG_LOCATION_FINISH;
            mHandler.sendMessage(msg);
        }

    }

    Handler mHandler = new Handler() {
        public void dispatchMessage(android.os.Message msg) {
            switch (msg.what) {
                //定位完成
                case Utils.MSG_LOCATION_FINISH:
                    String result = "";
                    try {
                        AMapLocation loc = (AMapLocation) msg.obj;
                        result = Utils.getLocationStr(loc, 1);
                        strMsg = result.split(",");
                        Toast.makeText(MainActivity.this, "定位成功", Toast.LENGTH_LONG).show();
                        textView.setText("地址:" + strMsg[0] + "\n" + "經    度:" + strMsg[1] + "\n" + "緯    度:" + strMsg[2]+"\n");
                        latLonPoint= new LatLonPoint(Double.valueOf(strMsg[2]), Double.valueOf(strMsg[1]));
                        initMap();
                    } catch (Exception e) {
                        Toast.makeText(MainActivity.this, "定位失敗", Toast.LENGTH_LONG).show();
                    }
                    break;
                default:
                    break;
            }
        };

    };


    public void Location() {
        // TODO Auto-generated method stub
        try {
            locationClient = new AMapLocationClient(this);
            locationOption = new AMapLocationClientOption();
            // 設置定位模式為低功耗模式
            locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            // 設置定位監聽
            locationClient.setLocationListener(this);
            locationOption.setOnceLocation(true);//設置為單次定位
            locationClient.setLocationOption(locationOption);// 設置定位參數
            // 啟動定位
            locationClient.startLocation();
            mHandler.sendEmptyMessage(Utils.MSG_LOCATION_START);
        } catch (Exception e) {
            Toast.makeText(MainActivity.this, "定位失敗", Toast.LENGTH_LONG).show();
        }
    }


    /**
     * 響應逆地理編碼圍欄
     */
    public void getAddress(final LatLonPoint latLonPoint) {
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 100,
                GeocodeSearch.AMAP);// 第一個參數表示一個Latlng,第二參數表示範圍多少米,第三個參數表示是網路   坐標系還是GPS原生坐標系
        geocoderSearch.getFromLocationAsyn(query);// 設置同步逆地理編碼請求
    }

    /**
     * 地理編碼查詢回調
     */
    @Override
    public void onGeocodeSearched(GeocodeResult result, int rCode) {

    }


    /**
     * 逆地理編碼回調
     */
    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
        if (rCode == 1000) {
            if (result != null && result.getRegeocodeAddress() != null
                    && result.getRegeocodeAddress().getFormatAddress() != null) {

                Toast.makeText(MainActivity.this,result.getRegeocodeAddress().getFormatAddress()
                        + "附近",Toast.LENGTH_LONG).show();
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                        AMapUtil.convertToLatLng(latLonPoint), 15));
                geoMarker.setPosition(AMapUtil.convertToLatLng(latLonPoint));
            } else {

            }
        } else {
        }
    }


    
    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必須重寫
     */
    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
}

在同級的文件下建立自己的類方法,調用到主代碼中

AMapUtil代碼為:

public class AMapUtil {
    /**
     * 判斷edittext是否null
     */
    public static String checkEditText(EditText editText) {
        if (editText != null && editText.getText() != null
                && !(editText.getText().toString().trim().equals(""))) {
            return editText.getText().toString().trim();
        } else {
            return "";
        }
    }

    public static Spanned stringToSpan(String src) {
        return src == null ? null : Html.fromHtml(src.replace("\n", "<br />"));
    }

    public static String colorFont(String src, String color) {
        StringBuffer strBuf = new StringBuffer();

        strBuf.append("<font color=").append(color).append(">").append(src)
                .append("</font>");
        return strBuf.toString();
    }

    public static String makeHtmlNewLine() {
        return "<br />";
    }

    public static String makeHtmlSpace(int number) {
        final String space = " ";
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < number; i++) {
            result.append(space);
        }
        return result.toString();
    }

    public static String getFriendlyLength(int lenMeter) {
        if (lenMeter > 10000) // 10 km
        {
            int dis = lenMeter / 1000;
            return dis + "";
        }

        if (lenMeter > 1000) {
            float dis = (float) lenMeter / 1000;
            DecimalFormat fnum = new DecimalFormat("##0.0");
            String dstr = fnum.format(dis);
            return dstr;
        }

        if (lenMeter > 100) {
            int dis = lenMeter / 50 * 50;
            return dis + "";
        }

        int dis = lenMeter / 10 * 10;
        if (dis == 0) {
            dis = 10;
        }

        return dis + "";
    }

    public static boolean IsEmptyOrNullString(String s) {
        return (s == null) || (s.trim().length() == 0);
    }

    /**
     * 把LatLng對象轉化為LatLonPoint對象
     */
    public static LatLonPoint convertToLatLonPoint(LatLng latlon) {
        return new LatLonPoint(latlon.latitude, latlon.longitude);
    }

    /**
     * 把LatLonPoint對象轉化為LatLon對象
     */
    public static LatLng convertToLatLng(LatLonPoint latLonPoint) {
        return new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude());
    }

    /**
     * 把集合體的LatLonPoint轉化為集合體的LatLng
     */
    public static ArrayList<LatLng> convertArrList(List<LatLonPoint> shapes) {
        ArrayList<LatLng> lineShapes = new ArrayList<LatLng>();
        for (LatLonPoint point : shapes) {
            LatLng latLngTemp = AMapUtil.convertToLatLng(point);
            lineShapes.add(latLngTemp);
        }
        return lineShapes;
    }

    /**
     * long類型時間格式化
     */
    public static String convertToTime(long time) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(time);
        return df.format(date);
    }

    public static final String HtmlBlack = "#000000";
    public static final String HtmlGray = "#808080";

    public static String getFriendlyTime(int second) {
        if (second > 3600) {
            int hour = second / 3600;
            int miniate = (second % 3600) / 60;
            return hour + "小時" + miniate + "分鐘";
        }
        if (second >= 60) {
            int miniate = second / 60;
            return miniate + "分鐘";
        }
        return second + "秒";
    }


    public static String getBusPathTitle(BusPath busPath) {
        if (busPath == null) {
            return String.valueOf("");
        }
        List<BusStep> busSetps = busPath.getSteps();
        if (busSetps == null) {
            return String.valueOf("");
        }
        StringBuffer sb = new StringBuffer();
        for (BusStep busStep : busSetps) {
            if (busStep.getBusLines().size() > 0) {
                RouteBusLineItem busline = busStep.getBusLines().get(0);
                if (busline == null) {
                    continue;
                }
                String buslineName = getSimpleBusLineName(busline.getBusLineName());
                sb.append(buslineName);
                sb.append(" > ");
            }
            if (busStep.getRailway() != null) {
                RouteRailwayItem railway = busStep.getRailway();
                sb.append(railway.getTrip() + "(" + railway.getDeparturestop().getName()
                        + " - " + railway.getArrivalstop().getName() + ")");
                sb.append(" > ");
            }
        }
        return sb.substring(0, sb.length() - 3);
    }

    public static String getBusPathDes(BusPath busPath) {
        if (busPath == null) {
            return String.valueOf("");
        }
        long second = busPath.getDuration();
        String time = getFriendlyTime((int) second);
        float subDistance = busPath.getDistance();
        String subDis = getFriendlyLength((int) subDistance);
        float walkDistance = busPath.getWalkDistance();
        String walkDis = getFriendlyLength((int) walkDistance);
        return String.valueOf(time + " | " + subDis + " | 步行" + walkDis);
    }

    public static String getSimpleBusLineName(String busLineName) {
        if (busLineName == null) {
            return String.valueOf("");
        }
        return busLineName.replaceAll("\\(.*?\\)", "");
    }


}

  

Utils的主代碼為:

public class Utils {


    /**
     * 開始定位
     */
    public final static int MSG_LOCATION_START = 0;
    /**
     * 定位完成
     */
    public final static int MSG_LOCATION_FINISH = 1;
    /**
     * 停止定位
     */

    /**
     * 根據定位結果返回定位信息的字元串
     *
     * @return
     */
    public synchronized static String getLocationStr(AMapLocation location, final int index) {
        if (null == location) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        //errCode等於0代表定位成功,其他的為定位失敗,具體的可以參照官網定位錯誤碼說明
        if (location.getErrorCode() == 0) {
            sb.append("定位成功" + "\n");
            sb.append("定位類型: " + location.getLocationType() + "\n");
            sb.append("經    度    : " + location.getLongitude() + "\n");
            sb.append("緯    度    : " + location.getLatitude() + "\n");
            sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
            sb.append("提供者    : " + location.getProvider() + "\n");




            if (location.getProvider().equalsIgnoreCase(
                    android.location.LocationManager.GPS_PROVIDER)) {
                // 以下信息只有提供者是GPS時才會有
                sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
                sb.append("角    度    : " + location.getBearing() + "\n");
                // 獲取當前提供定位服務的衛星個數
                sb.append("星    數    : "
                        + location.getSatellites() + "\n");
            } else {
                // 提供者是GPS時是沒有以下信息的
                sb.append("國    家    : " + location.getCountry() + "\n");
                sb.append("省            : " + location.getProvince() + "\n");
                sb.append("市            : " + location.getCity() + "\n");
                sb.append("城市編碼 : " + location.getCityCode() + "\n");
                sb.append("區            : " + location.getDistrict() + "\n");
                sb.append("區域 碼   : " + location.getAdCode() + "\n");
                sb.append("地    址    : " + location.getAddress() + "\n");
                sb.append("興趣點    : " + location.getPoiName() + "\n");
                return (location.getAddress() + "," + location.getLongitude() + "," + location.getLatitude());
            }
//這個方法可以進行反向的地理圍欄圈定          
  //if(location.getLatitude()==“緯度”||location.getLongitude()==“經度”){
            //    sb.append("可以簽到"+"\n");
              //  return sb.toString();

          //  }
          //  else {
           //     sb.append("不可簽到"+"\n");

        //    }

    //    }

        else {
            //定位失敗
            sb.append("定位失敗" + "\n");
            sb.append("錯誤碼:" + location.getErrorCode() + "\n");
            sb.append("錯誤信息:" + location.getErrorInfo() + "\n");
            sb.append("錯誤描述:" + location.getLocationDetail() + "\n");
            return sb.toString();
        }
        return sb.toString();

    }



}

  如果要使用那個逆地理的編碼圍欄,你需要自己設定button控制項的響應事件,通過返回值來控制button是否開啟

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一、來源 在電腦科學中,柯里化(Currying)是把接受多個參數的函數變換成接受一個單一參數(最初函數的第一個參數)的函數,並且返回接受餘下的參數且返回結果的新函數的技術。這個技術由 Christopher Strachey 以邏輯學家 Haskell Curry 命名的,儘管它是 Moses ...
  • 前端變化飛快,掌握一門前端框架在當下開發中必不可少,vue.js作為三大框架之一,擁有友好的中文文檔,平緩的學習曲線,在經過一段時間的學習之後,自己也用vue實現了一個簡單的小dome,項目雖小,但都用到了當下最常用的技術,可謂是麻雀雖小、五臟俱全。 ...
  • <header></header> 頁眉 主要用於頁面的頭部的信息介紹,也可用於板塊頭部 <hgroup></hgroup> 頁面上的一個標題組合 一個標題和一個子標題,或者標語的組合 <hgroup> <h1>妙味課堂</h1> <h2>帶您進入富有人情味的IT培訓</h2> </hgroup> ...
  • 代碼管理工具一開始用的確會有點懵,但是永久了就會發現都是那幾下套路,記錄下來 托管好了代碼一般起衝突了還是想重新搞一下,有個萬能的重置操作,那就是重新關聯svn項目,以前有時更換地址也是,發現遇到很多衝突問題,因為前面創建了文件,但是後來在伺服器上刪除了,結果衝突更換地址,發現衝突了,你又還原不了, ...
  • 什麼是EventBus 由greenrobot組織貢獻(該組織還貢獻了greenDAO),一個Android事件發佈/訂閱輕量級框架,功能:通過解耦發佈者和訂閱者簡化Android事件傳遞,EventBus可以代替Android傳統的Intent,Handler,Broadcast或介面函數,在Fr ...
  • 聲明 AS已經是Android開發的主流工具了,但是學校教學用的還是eclipse,很多同學不知道如何入門。網上看到一位大神整理得很好的教程,轉載過來,希望可以幫到有需要的人。 生命壹號:http://www.cnblogs.com/smyhvae/ 文章來源:http://www.cnblogs. ...
  • 0x00前言 一個安卓應用可以被調試的條件是應用AndroidManifest.xml顯示指定android:debuggable="true",如果沒有設置android:debuggable的值,則預設android:debuggable="false",所以發佈的應用大部分都是不可調試的,如果 ...
  • 一、VideoView及其相關組件總結 在Android中,播放視頻有2種方式,第一種方式是使用MediaPlayer結合SurfaceView來播放,通過MediaPlayer來控制視頻的播放、暫停、進度等,而通過SurfaceView來顯示視頻內容;第二種方式是使用VideoView來播放,這個 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...