[android learning notes] basic positioning and map display of Gaud map

Keywords: Android Amap network xml

[overview] there are quite a lot of problems in the use of Golder at the beginning. Combined with some cases on the Internet, some summaries are made.

[simple process] 1. Get key - > 2. Configure Android Studio - > 3. Use

[step 1] get the key

Address: https://lbs.amap.com/dev/key/app

① Get SHA1 and follow the document

Document address: https://lbs.amap.com/faq/top/hot-questions/249

② Get the package of Android manifest.xml configuration file

[step 2] configuration of Android studio

① Download SDK development package

Address: https://lbs.amap.com/api/android-location-sdk/download/

After decompression, put the resulting jar package under libs -- the other four so files under SRC - > main - > jnilibs

② Configure Android studio

1. Configure dependencies in the build.gradle file of the main project

Address: https://lbs.amap.com/api/android-location-sdk/guide/create-project/android-studio-create-project

2. Configuration of permissions, etc

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="menu.bottombar.amap">

    <!-- Allows applications to open network sockets  -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Allow program settings built in sd Write permission of card -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!-- Allow programs to get network status -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!-- Allow program access WiFi network information -->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <!-- Allow programs to read and write mobile status and identity -->
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <!-- For network location -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <!-- For access GPS Location -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <!-- For acquisition wifi Access to, wifi Information will be used for network location -->
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <!-- Used to read the current status of the phone -->
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <!-- Used to request a call A-GPS Modular -->
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <!-- Access to operator information to support the provision of operator information related interfaces -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!-- For access wifi Network information, wifi Information will be used for network location -->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <!-- This permission is used to get wifi Access to, wifi Information will be used for network location -->
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <!-- For access to the network, network positioning needs to be online -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Used to read the current status of the phone -->
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <!-- Write extended storage, write data to expansion card, for writing cache location data -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

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

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

        <activity android:name=".MapActivity"></activity>
    </application>

</manifest>

Note: meta data and service should be written in the application.

[step 3] use of goldmap SDK

activity_main:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text_map"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:gravity="center"
        android:text="Positioning......."
        android:textColor="@color/colorAccent"
        android:textSize="22dp" />
    <Button
        android:id="@+id/btn"
        android:layout_below="@id/text_map"
        android:layout_width="wrap_content"
        android:layout_height="35dp"
        android:text="consult a map"/>

</RelativeLayout>

MainActivity:

package menu.bottombar.amap;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
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;

public class MainActivity extends AppCompatActivity implements AMapLocationListener {
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private TextView textView;
    private String[] strMsg;

    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        textView = (TextView) findViewById(R.id.text_map);
        Location();
    }

    private void initView() {
        button=(Button)findViewById(R.id.btn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(MainActivity.this,MapActivity.class);
                startActivity(intent);
            }
        });
    }

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

    }

    Handler mHandler = new Handler() {
        public void dispatchMessage(android.os.Message msg) {
            switch (msg.what) {
                //Location complete
                case GPSUtils.MSG_LOCATION_FINISH:
                    String result = "";
                    try {
                        AMapLocation loc = (AMapLocation) msg.obj;
                        result = GPSUtils.getLocationStr(loc, 1);
                        strMsg = result.split(",");
                        Toast.makeText(MainActivity.this, "Successful positioning", Toast.LENGTH_LONG).show();
                        textView.setText("Address:" + strMsg[0] + "\n" + "through    Degree:" + strMsg[1] + "\n" + "weft    Degree:" + strMsg[1]);
                    } catch (Exception e) {
                        Toast.makeText(MainActivity.this, "seek failed", Toast.LENGTH_LONG).show();
                    }
                    break;
                default:
                    break;
            }
        };

    };

    public void Location() {
        // TODO Auto-generated method stub
        try {
            locationClient = new AMapLocationClient(this);
            locationOption = new AMapLocationClientOption();
            // Set positioning mode to low power mode
            locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
            // Set location monitoring
            locationClient.setLocationListener(this);
            locationOption.setOnceLocation(true);//Set to single positioning
            locationClient.setLocationOption(locationOption);// Set positioning parameters
            // Start location
            locationClient.startLocation();
            mHandler.sendEmptyMessage(GPSUtils.MSG_LOCATION_START);
        } catch (Exception e) {
            Toast.makeText(MainActivity.this, "seek failed", Toast.LENGTH_LONG).show();
        }
    }

}

GPSUtils:

package menu.bottombar.amap;

import com.amap.api.location.AMapLocation;

public class GPSUtils {
        /**
         * Start positioning
         */
        public final static int MSG_LOCATION_START = 0;
        /**
         * Location complete
         */
        public final static int MSG_LOCATION_FINISH = 1;
        /**
         * Stop location
         */

        /**
         * Returns a string of location information based on the location result
         *
         * @return
         */
        public synchronized static String getLocationStr(AMapLocation location, final int index) {
            if (null == location) {
                return null;
            }
            StringBuffer sb = new StringBuffer();
            //errCode equal to 0 means successful positioning, others are positioning failures. For details, please refer to the description of positioning error code on the official website
            if (location.getErrorCode() == 0) {
                sb.append("Successful positioning" + "\n");
                sb.append("Location type: " + location.getLocationType() + "\n");
                sb.append("through    degree    : " + location.getLongitude() + "\n");
                sb.append("weft    degree    : " + location.getLatitude() + "\n");
                sb.append("essence    degree    : " + location.getAccuracy() + "rice" + "\n");
                sb.append("Provider    : " + location.getProvider() + "\n");

                if (location.getProvider().equalsIgnoreCase(
                        android.location.LocationManager.GPS_PROVIDER)) {
                    // The following information is only available if the provider is GPS
                    sb.append("speed    degree    : " + location.getSpeed() + "rice/second" + "\n");
                    sb.append("horn    degree    : " + location.getBearing() + "\n");
                    // Obtain the number of satellites currently providing positioning services
                    sb.append("Star    number    : "
                            + location.getSatellites() + "\n");
                } else {
                    // When the provider is GPS, it does not have the following information
                    sb.append("country    home    : " + location.getCountry() + "\n");
                    sb.append("province            : " + location.getProvince() + "\n");
                    sb.append("city            : " + location.getCity() + "\n");
                    sb.append("City coding : " + location.getCityCode() + "\n");
                    sb.append("area            : " + location.getDistrict() + "\n");
                    sb.append("Area code   : " + location.getAdCode() + "\n");
                    sb.append("land    site    : " + location.getAddress() + "\n");
                    sb.append("Interest point    : " + location.getPoiName() + "\n");
                    return (location.getAddress() + "," + location.getLongitude() + "," + location.getLatitude());
                }
            } else {
                //seek failed
                sb.append("seek failed" + "\n");
                sb.append("Error code:" + location.getErrorCode() + "\n");
                sb.append("error message:" + location.getErrorInfo() + "\n");
                sb.append("Wrong description:" + location.getLocationDetail() + "\n");
                return sb.toString();
            }
            return sb.toString();
        }

}

Test results:

Activity map:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapActivity">

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

    </com.amap.api.maps.MapView>
</LinearLayout>

Note: remember to use com.amap.api.maps.MapView

MapActivity:

(the code here refers to https://blog.csdn.net/bai981002/article/details/78730044)

package menu.bottombar.amap;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
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.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.LatLng;

public class MapActivity extends AppCompatActivity implements LocationSource, AMapLocationListener {
    //AMap is a map object
    private AMap aMap;
    private MapView mapView;
    //Declare AMapLocationClient class object and locate initiator
    private AMapLocationClient mLocationClient = null;
    //Declare mLocationOption object, locate parameter
    public AMapLocationClientOption mLocationOption = null;
    //Declare mListener object, locate listener
    private OnLocationChangedListener mListener = null;
    //Identification, which is used to determine whether to display positioning information and user relocation only once
    private boolean isFirstLoc = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        //Get map control reference
        mapView = (MapView) findViewById(R.id.map);
        //When the activity executes onCreate, execute mMapView.onCreate(savedInstanceState) to realize map lifecycle management
        mapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mapView.getMap();
            //Set the display positioning button and click
            UiSettings settings = aMap.getUiSettings();
            aMap.setLocationSource(this);//Monitor with location set
            // Show positioning button or not
            settings.setMyLocationButtonEnabled(true);
            aMap.setMyLocationEnabled(true);//Display the location layer and trigger the location. The default is flash
        }
        //Start positioning
        location();
    }

    private void location() {
        //Initialize positioning
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //Set location callback listening
        mLocationClient.setLocationListener(this);
        //Initialize positioning parameters
        mLocationOption = new AMapLocationClientOption();
        //Set the positioning mode to high accuracy mode, battery saving to low power consumption mode, and device sensors to device only mode
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //Set whether to return address information (default return address information)
        mLocationOption.setNeedAddress(true);
        //Set whether to locate only once, default to false
        mLocationOption.setOnceLocation(false);
        //Set whether to force refresh WIFI. The default is forced refresh
        mLocationOption.setWifiActiveScan(true);
        //Set whether to allow analog location. The default value is false. Analog location is not allowed
        mLocationOption.setMockEnable(false);
        //Set the positioning interval, in milliseconds, the default is 2000ms
        mLocationOption.setInterval(2000);
        //Set positioning parameters for positioning client objects
        mLocationClient.setLocationOption(mLocationOption);
        //Start location
        mLocationClient.startLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //When the activity executes onDestroy, execute mMapView.onDestroy() to implement Map lifecycle management
        mapView.onDestroy();
        mLocationClient.stopLocation();//Stop location
        mLocationClient.onDestroy();//Destroy the location client.
    }

    @Override
    protected void onResume() {
        super.onResume();
        //When the activity performs onResume, execute mMapView.onResume() to implement Map lifecycle management
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //When the activity executes onPause, execute mMapView.onPause() to realize map lifecycle management
        mapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //When the activity executes onSaveInstanceState, execute mMapView.onSaveInstanceState (outState) to realize map lifecycle management
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                //Locate successful callback information and set related messages
                aMapLocation.getLocationType();//Obtain the source of current positioning results, such as network positioning results. See the official positioning type table for details
                aMapLocation.getLatitude();//Latitude acquisition
                aMapLocation.getLongitude();//Acquire longitude
                aMapLocation.getAccuracy();//Obtain precision 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 the isNeedAddress is set to false in the option, there will be address information in the network positioning result without this result. GPS positioning will not return address information.
                aMapLocation.getCountry();//National Information
                aMapLocation.getProvince();//Provincial Information
                aMapLocation.getCity();//City Information
                aMapLocation.getDistrict();//Urban information
                aMapLocation.getStreet();//Street information
                aMapLocation.getStreetNum();//Street number information
                aMapLocation.getCityCode();//City coding
                aMapLocation.getAdCode();//Area coding

                // If the flag bit is not set, when you drag the map again, it will continuously move the map to the current position
                if (isFirstLoc) {
                    //Set zoom level
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
                    //Move map to anchor point
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
                    //Click the positioning button to move the center of the map to the positioning point
                    mListener.onLocationChanged(aMapLocation);
                    //Add tack
                    //  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());
                    Toast.makeText(getApplicationContext(), buffer.toString(), Toast.LENGTH_LONG).show();
                    isFirstLoc = false;
                }


            } else {
                //ErrCode is the error code and errInfo is the error message. See the error code table for details.
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
                Toast.makeText(getApplicationContext(), "seek failed", Toast.LENGTH_LONG).show();
            }
        }
    }


    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {
        mListener = null;
    }

}

Implementation page:

Demo:

Posted by suresh_nsnguys on Sun, 05 Jan 2020 11:14:20 -0800