Gold map positioning, and calculate the current anchor point and target point distance

Source: Internet
Author: User

1. Download the gold map and location SDK to copy the Arm folder and jar package from the demo to Libs.

2.gradle file

Apply plugin:'com.android.application'Android {compilesdkversion atbuildtoolsversion"23.0.3"sourcesets{main{jnilibs.srcdirs=['Libs']}} defaultconfig {ApplicationID"Myapplication.com.mygaode"minsdkversion thetargetsdkversion atVersioncode1Versionname"1.0"} buildtypes {release {minifyenabledfalseproguardfiles Getdefaultproguardfile ('Proguard-android.txt'),'Proguard-rules.pro'}}}dependencies {compile filetree (include: ['*.jar'], dir:'Libs') Testcompile'junit:junit:4.12'Compile'com.android.support:appcompat-v7:23.3.0'Compile files ('Libs/amap_location_v3.2.0_20161205.jar') compile files ('Libs/amap_search_v3.6.1_20161122.jar') compile files ('Libs/android_map3d_sdk_v4.1.3_20161208.jar')}

3. Configuration file:

Permission:< the copy of the website, there may be duplicate >

   <!--allow programs to set write permissions on the built-in SD card -    <uses-permissionAndroid:name= "Android.permission.WRITE_EXTERNAL_STORAGE" />    <!--allow programs to get network status -    <uses-permissionAndroid:name= "Android.permission.ACCESS_NETWORK_STATE" />    <!--allow programs to access WiFi network information -    <uses-permissionAndroid:name= "Android.permission.ACCESS_WIFI_STATE" />    <!--allows programs to read and write phone status and identity -    <uses-permissionAndroid:name= "Android.permission.READ_PHONE_STATE" />    <!--allow programs to access cellid or WiFi hotspots to get a rough location -    <uses-permissionAndroid:name= "Android.permission.ACCESS_COARSE_LOCATION" />    <!--for network positioning -    <uses-permissionAndroid:name= "Android.permission.ACCESS_COARSE_LOCATION"></uses-permission>    <!--used to access GPS positioning -    <uses-permissionAndroid:name= "Android.permission.ACCESS_FINE_LOCATION"></uses-permission>    <!--used to obtain carrier information to support interfaces that provide information about the carrier -    <uses-permissionAndroid:name= "Android.permission.ACCESS_NETWORK_STATE"></uses-permission>    <!--for accessing WiFi network information, WiFi information will be used for network location -    <uses-permissionAndroid:name= "Android.permission.ACCESS_WIFI_STATE"></uses-permission>    <!--To get access to WiFi, WiFi information is used for network location -    <uses-permissionAndroid:name= "Android.permission.CHANGE_WIFI_STATE"></uses-permission>    <!--for access to the network, network location requires Internet access -    <uses-permissionAndroid:name= "Android.permission.INTERNET"></uses-permission>    <!--used to read the current state of the phone -    <uses-permissionAndroid:name= "Android.permission.READ_PHONE_STATE"></uses-permission>    <!--for writing cached data to an extended memory card -    <uses-permissionAndroid:name= "Android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>    <!--used to request a call to the A-gps module -    <uses-permissionAndroid:name= "Android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"></uses-permission>
    <!--    German Akey        -- <  android:name= "Com.amap.api.location.APSService"></Service  >        <meta-data            android:name= " Com.amap.api.v2.apikey "            android:value=" The key value you wrote here "            />

3. The layout has only one textview to display the distance data:

The activity code is as follows:

Package Myapplication.com.mygaode;import Android.os.handler;import Android.os.message;import Android.support.v7.app.appcompatactivity;import Android.os.bundle;import Android.util.log;import Android.widget.textview;import Android.widget.toast;import Com.amap.api.location.amaplocation;import Com.amap.api.location.amaplocationclient;import Com.amap.api.location.amaplocationclientoption;import Com.amap.api.location.amaplocationlistener;import Com.amap.api.maps.amaputils;import Com.amap.api.maps.model.latlng;import Java.text.simpledateformat;import Java.util.date;public class MainActivity    Extends Appcompatactivity implements Amaplocationlistener {double lat=0,lon=0;    TextView TextView;    /** * Gold Map Location * * *//DECLARE Amaplocationclient class object, locate initiator private amaplocationclient mlocationclient = null;    Declares the Mlocationoption object, locates the parameter public amaplocationclientoption mlocationoption = null;   Declares the Mlistener object, locates the listener//identity, determines whether to display only one location information and the user repositions private Boolean isfirstloc = true; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        textview= (TextView) Findviewbyid (R.id.textview);    Location (); }/** * * */private void location () {//Initialize positioning mlocationclient = new Amaplocationclient (g        Etapplicationcontext ());        Set positioning callback Listener Mlocationclient.setlocationlistener (this);        Initialize positional parameters mlocationoption = new Amaplocationclientoption (); Set the positioning mode to hight_accuracy high precision mode, battery_saving for low power mode, Device_sensors is device mode only Mlocationoption.setlocationmode (        AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);        Sets whether to return address information (default return address information) mlocationoption.setneedaddress (TRUE);        Sets whether to locate only once, the default is False Mlocationoption.setoncelocation (false);        Set whether to force refresh of WiFi, default to force refresh Mlocationoption.setwifiactivescan (true); Set whether to allow impersonation location, default to False, do not allow analog location Mlocationoption.setmockenabLe (false);        Set the positioning interval, in milliseconds, the default is 2000ms Mlocationoption.setinterval (2000);        Set positioning Parameters Mlocationclient.setlocationoption (mlocationoption) for locating client objects;    Start positioning mlocationclient.startlocation ();    }/** * Method rewrite * */@Override protected void Onresume () {super.onresume ();    } @Override protected void OnPause () {super.onpause ();        } @Override protected void OnDestroy () {Super.ondestroy ();    Mlocationclient.stoplocation ();//Stop positioning Mlocationclient.ondestroy ();//Destroy the location client.    } @Override protected void Onsaveinstancestate (Bundle outstate) {super.onsaveinstancestate (outstate); }/** * */@Override public void onlocationchanged (Amaplocation amaplocation) {if (amaploc Ation! = null) {if (amaplocation.geterrorcode () = = 0) {//Locate the successful callback information, set the related message Amaplo Cation.getlocationtype ();//Get the current location result source, such as network location results, see official Positioning Type table doUble la= amaplocation.getlatitude ();//Get Latitude Double lo= amaplocation.getlongitude ();//Get Longitude AMa                Plocation.getaccuracy ();//Get accuracy information simpledateformat df = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");                Date date = new Date (Amaplocation.gettime ()); Df.format (date),///Location time amaplocation.getaddress ();//Address, if set Isneedaddress to false in option, there is no result, address information in the network location result, G                The PS locator does not return address information. Amaplocation.getcountry ();//National information amaplocation.getprovince ();//Province information amaplocation.getcity ();//City City Information Amaplocation.getdistrict ();//Urban Information amaplocation.getstreet ();//Street Information Amaploc Ation.getstreetnum ();//Street number information amaplocation.getcitycode ();//City Code Amaplocation.getadcode ();//                    Area code//If you do not set the flag bit, and then drag the map, it will continue to move the map to the current position if (Isfirstloc) {//Set the zoom level Move the map to the anchor Point//PointClick the Position button to move the center of the map to the anchor Point//Add pushpin//Amap.addmarker (Getmarkeroptions (amaplocation));                    Get location information StringBuffer buffer = new StringBuffer ();                            Buffer.append (Amaplocation.getcountry () + "" + amaplocation.getprovince () + ""                            + amaplocation.getcity () + "" + amaplocation.getprovince () + ""                            + amaplocation.getdistrict () + "" + amaplocation.getstreet () + ""                    + Amaplocation.getstreetnum ());                    Lat=la;                    Lon=lo;                    Message Message=handler.obtainmessage ();                    LATLNG latlng=new latlng (Lat,lon);                    MESSAGE.OBJ=LATLNG;                 Handler.sendmessage (message); Toast.maketext (Getapplicationcontext (), buffer.tostring () +la+ "*" +lo, Toast.length_long). Show ();                Isfirstloc = false;                }} else {//Display error message Errcode is an error code, Errinfo is an error message, see the Error code table.                        LOG.E ("Amaperror", "Location Error, Errcode:" + amaplocation.geterrorcode () + ", Errinfo:"                + Amaplocation.geterrorinfo ());            Toast.maketext (Getapplicationcontext (), "failed to locate", Toast.length_long). Show ();            }}} Handler handler=new Handler () {@Override public void Handlemessage (Message msg) {           Super.handlemessage (msg);            LATLNG latlng= (LATLNG) msg.obj;            Lat=latlng.latitude;            Lon=latlng.longitude;            /** * Calculates the distance between the current anchor point and the target point, and displays the unit in meters */latlng latlng2=new latlng (32.101937,118.777595);            float distance = amaputils.calculatelinedistance (latlng,latlng2); Textview.settext ("Current anchor point lat:" +lat+ "LON:" +lon+ "\ n Target point: lat:32.101937, lon:118.777595" + "\ n Distance:" +distance+"M"); }    };}

Gold map positioning, and calculate the current anchor point and target point distance

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.