Android Quick Master High-speed Map SDK (contains practical projects)

Source: Internet
Author: User
Tags sha1

Last week I studied the SDK for the gold map and the aurora push and needed it in the project, but it took a while to read the documentation and demo code. (Have to spit groove part of the document really does not make sense, only a simple instance of the program comments are not, the context is not docking, really drunk), so intends to write the most straightforward steps in the blog, but also hope to help not use the two SDK for the small partners, less detours, improve work efficiency.


This article mainly introduces the use steps of the German map SDK:

This includes access to key, to the guide package, to the layout file, and to the encoding implementation.

There are also two of the most commonly used features:

Implement positioning itself.

Search location and display small blue dots based on place names or coordinates.

First, get high-tak key:

Click here to enter The Gold console, click Create App, enter the app name and app type.


Once the app is created, click Add Key to start adding a new key:


There are two ways to get the SHA1 code:

1. Eclipse can view the current app's SHA1 value directly from Android----preferances.

2, Androidstudio users have two ways, the first through the command line statement to obtain, but this kind of signature to be a little more trouble, the second way the simplest direct use of a method to output the current application of the SHA1 value, copied down can be, the method is as follows (Gaodwin file provided):

public static String SHA1 (context context) {try {packageinfo info = Context.getpackagemanager (). Getpackageinfo        (Context.getpackagename (), packagemanager.get_signatures);        byte[] cert = Info.signatures[0].tobytearray ();        MessageDigest MD = messagedigest.getinstance ("SHA1");        byte[] PublicKey = md.digest (cert);        StringBuffer hexstring = new StringBuffer (); for (int i = 0; i < publickey.length; i++) {String appendString = integer.tohexstring (0xFF & publickey[            I]). toUpperCase (locale.us);            if (appendstring.length () = = 1) hexstring.append ("0");            Hexstring.append (appendString);        Hexstring.append (":");        The String result = hexstring.tostring ();        LOG.D ("Xiaojingyu", result);    Return result.substring (0, Result.length ()-1);    } catch (Packagemanager.namenotfoundexception e) {e.printstacktrace (); } catch (NosuchalgorithmexCeption e) {e.printstacktrace (); } return null;
After committing, we will get a string of characters similar to 38bcab8bxxxxxx5bed57ba835e1, which is the key we need to develop.


Second, guide package:

Eclipse won't say it, just put the bag in the Libs.

Androidstudio is a bit more complicated, but that is, put it in Libs and add it to the library.

The following are some of the packages that need to be used:

and package


Third, access to access:

The required permissions are added into the Androidmainfest.xml file:

<!--for network positioning--><uses-permission android:name= "Android.permission.ACCESS_COARSE_LOCATION" ></ uses-permission><!--used to access GPS positioning--><uses-permission android:name= "android.permission.ACCESS_FINE_ Location ></uses-permission><!--Get carrier information to support the interface that provides carrier information--><uses-permission android:name= " Android.permission.ACCESS_NETWORK_STATE "></uses-permission><!--for accessing WiFi network information, WiFi information is used for network location-- <uses-permission android:name= "Android.permission.ACCESS_WIFI_STATE" ></uses-permission><!-- This permission is used to get WiFi access, WiFi information will be used for network location--><uses-permission android:name= "Android.permission.CHANGE_WIFI_STATE" ></uses-permission><!--used to access the network, network location requires internet--><uses-permission android:name= " Android.permission.INTERNET "></uses-permission><!--used to read the current status of the phone--><uses-permission android: Name= "Android.permission.READ_PHONE_STATE" ></uses-permission><!--write to extended storage, write data to the expansion card for write cache location data-- <uses-permission android:name= "Android.permisSion. Write_external_storage "></uses-permission>


Four, the implementation of the code:

The first is the layout file:

Set the Mapview specified by the German SDK:

        <com.amap.api.maps.mapview            android:id= "@+id/map"            android:layout_width= "Match_parent"            android: layout_height= "0DP"            android:layout_margintop= "10DP"            android:layout_weight= "1"            android:focusable= " True "            android:focusableintouchmode=" true ">        </com.amap.api.maps.MapView>

The code is then started to be written. Since the Mapview is used in the layout file, it must be initialized in the code:

Mapview Mmapview = null;
What is the role of this mapview? After reading the code (the document will not tell you) we can see that it is the view of the map and need to implement the life cycle management of the map:

        Mmapview = (Mapview) V.findviewbyid (r.id.map);        Perform mmapview.oncreate (savedinstancestate) when activity executes onCreate to achieve Map lifecycle management        mmapview.oncreate ( Savedinstancestate);
Of course there is a key class of AMAP, which plays a fundamental role in the management of the map and the control interface, and we can initialize the AMAP instance as follows when initializing:

        if (AMap = = null) {            AMAP = Mmapview.getmap ();            Amap.movecamera (cameraupdatefactory.zoomto (0)); Set the zoom to 0, then one comes in to show the entire mainland China            Amap.setlocationsource (this);//Set the location monitor            amap.getuisettings (). Setmylocationbuttonenabled (TRUE);//sets whether the Default Positioning button displays            amap.setmylocationenabled (TRUE);//set to True to indicate that the positioning layer is displayed and can trigger positioning. False means to hide the anchor layer and not trigger the positioning, the default is False            //Set the positioning type is the positioning mode, can be positioned, followed or the map according to the direction of rotation of several            Amap.setmylocationtype (amap.location _type_locate);        }


To implement the current position system small blue dot:

We can use the current activity to implement AMAP positioning monitoring Amaplocationlistener, and rewrite its positioning method:

    @Override public    void onlocationchanged (Amaplocation amaplocation) {        if (mlistener! = null && Amaplocation! = null) {            if (amaplocation! = null                    && amaplocation.geterrorcode () = = 0) {                Mlistener.onlocationchanged (amaplocation);//display system small blue dot            } else {                String errtext = "Location failed," + Amaplocation.geterrorcode () + ":" + amaplocation.geterrorinfo ();                LOG.E ("Amaperr", Errtext);}}    
There is also a place to change the listening: Onlocationchangedlistener, through its method onlocationchanged (amaplocation) to achieve the change of location on the map!


Implementing a response geocoding (entering place-name positioning to a specific location):

You can see that you need to set up the location listener in the AMAP initialization code, so you need to implement the Locationsource interface for the current activity, and rewrite the active location and stop locating the two interface methods:

    /** * Activate location */@Override public void Activate (Onlocationchangedlistener listener) {LOG.D ("Xiaojin        Gyu "," activate ");        Mlistener = listener;            if (mlocationclient = = null) {mlocationclient = new Amaplocationclient (getactivity ());            Mlocationoption = new Amaplocationclientoption ();            Set the location monitoring Mlocationclient.setlocationlistener (this);            Set to high precision positioning mode Mlocationoption.setlocationmode (AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);            Set positioning Parameters Mlocationclient.setlocationoption (mlocationoption);            This method initiates a location request every fixed time, in order to reduce power consumption or network traffic consumption,//Note the interval for setting the appropriate location time (minimum interval support is 2000ms), and call the Stoplocation () method at the appropriate time to cancel the location request At the end of the positioning, call the OnDestroy () method in the appropriate life cycle//In the case of a single location, no need to call the Stoplocation () method to remove the request if the location is successful or not, the Location SDK will remove the ML        Ocationclient.startlocation (); }}/** * Stop positioning */@Override public void Deactivate () {LOG.D("Xiaojingyu", "deactivate");        Mlistener = null;            if (mlocationclient! = null) {mlocationclient.stoplocation ();        Mlocationclient.ondestroy ();    } mlocationclient = null; }
A targeted client object and an option location object are needed here.

Remember to declare:

Null
mlocationoption null;


Next we need to declare and initialize two search components:

// Search Components  geocodersearch;  geomarker;

All need to be initialized after OnCreate:

Geocodersearch = new Geocodesearch (getactivity ());        Geocodersearch.setongeocodesearchlistener (this);

            Geomarker = Amap.addmarker (new Markeroptions (). Anchor (0.5f, 0.5f)                    . Icon (bitmapdescriptorfactory                            . Defaultmarker (Bitmapdescriptorfactory.hue_blue));
Where Geomarker is used to show the small blue dots after successful positioning.
Next, we can write a specific geocoding method:

    /**     * Response geocoding */public    void Getlatlon (final String name) {        //showdialog ();        Geocodequery query = new Geocodequery (name, "0086");//The first parameter represents the address, the second parameter indicates the query city, Chinese or Chinese full spelling, Citycode, Adcode,        Geocodersearch.getfromlocationnameasyn (query);//Set Synchronous geocoding request    }
The second parameter I set to 0086 is China's area code, which can be found nationwide. For example, I only set the growth of the sand area code 0731, then I can only enter the name of Changsha to find, and then check for example, Yueyang is not found.

Then callback Geocodersearch's listener method to achieve the positioning:

    @Override public void ongeocodesearched (geocoderesult result, int rCode) {//dismissdialog (); if (RCode = =) {if (result! = null && result.getgeocodeaddresslist () = null &A mp;& result.getgeocodeaddresslist (). Size () > 0) {geocodeaddress address = Result.getgeocodeaddressl                IST (). Get (0); Amap.animatecamera (Cameraupdatefactory.newlatlngzoom (AMAPUTIL.CONVERTTOLATLNG (address.getLatLonPoi                NT ()), 15));                Geomarker.setposition (AMAPUTIL.CONVERTTOLATLNG (address. Getlatlonpoint ()));                Addressname = "Latitude and longitude Value:" + address.getlatlonpoint () + "\ n Location Description:" + address.getformataddress ();            Toastutil.show (Getactivity (), addressname); } else {toastutil.show (getactivity), "No query to results!"            ");        }} else {Toastutil.showerror (getactivity (), RCode); }    } 

The so-called inverse geocoding is actually passing in the coordinate values and then implementing the positioning, similar to the corresponding geocoding above, here is no longer implemented again.

This is probably the function you use, if you need additional features, you can refer to the official documentation of the German SDK:
http://lbs.amap.com/api/android-location-sdk/guide/android-location/getlocation/

Finally, I finally realized the effect of the motion diagram:


Because it is related to the project, it is not possible to paste all the source code.

A friend of the question in the comment area, I will answer each.












To implement the current position system small blue dot:

We can use the current activity to implement AMAP positioning monitoring Amaplocationlistener, and rewrite its positioning method:

    @Override public    void onlocationchanged (Amaplocation amaplocation) {        if (mlistener! = null && Amaplocation! = null) {            if (amaplocation! = null                    && amaplocation.geterrorcode () = = 0) {                Mlistener.onlocationchanged (amaplocation);//display system small blue dot            } else {                String errtext = "Location failed," + Amaplocation.geterrorcode () + ":" + amaplocation.geterrorinfo ();                LOG.E ("Amaperr", Errtext);}}    
There is also a place to change the listening: Onlocationchangedlistener, through its method onlocationchanged (amaplocation) to achieve the change of location on the map!


Android Quick Master High-speed Map SDK (contains practical projects)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.