Recently the project used gaode map, so to write an article about the use of gaode steps and methods, I hope to be useful to everyone!
1. Registration + Configuration
Needless to say, to use Autonavi map first to go to autonavi open platform to register as a developer (lbs.amap.com/), to register as autonavi developers need to be divided into three steps: the first step, registered Autonavi developers; Step 2, go to the console and create the application. The third step is to obtain the Key(see figure below, pay attention to the naming convention,SHA1 is worth obtaining online! Easy).
To get the key
After ok, go to the official website to download autonavi SDK(lbs.amap.com/api/android…) . Jar file and an armeabi folder. After that,(1) copy the jar package to your libs directory and (2) create the jniLibs folder in the main directory Copy the armeabi folder to this directory, or the downloaded so library to this directory if it already exists. See the figure (you can also refer to the second configuration mode on Autonavi’s official website):
Studio Configuration Engineering
Don’t forget to add the File dependency:
FileDependencies
All right, so we’re ready for the code.
Map of 2.
1. Configure the key in the manifest file:
1
Copy the code
2. Configure permissions (configure the following pile, and don’t worry about permissions bugs):
Copy the code
3. Load map controls in the layout file:
Copy the code
4. Just add the following lines of code to onCreate() and amap will appear!
MapView mapView = (MapView) findViewById(R.id.map); // Find the map control mapView.onCreate(savedInstanceState); // This method must be overridden by AMap AMap = mapView.getmap (); // Get a map objectCopy the code
Isn’t it easy? Again I still want to say, gaode map soft power and Baidu map is a gap, but gaode’s development documents than Baidu is very human! Now let’s use the location function to add dots on the map for fun.
3. Locate + add markers
The first way (the foundation, can refer to the website, the link here: lbs.amap.com/api/android…). :
MLocationClient = new AMapLocationClient(getApplicationContext()); // Initialize the AMapLocationClientOption object mLocationOption = new AMapLocationClientOption(); // Set the positioning mode to high-precision mode. mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy); / / set the orientation correction to monitor mLocationClient. SetLocationListener (this); / / get a positioning results mLocationOption. SetOnceLocation (true); / / set the return address information (the default return address information) mLocationOption. SetNeedAddress (true); / / to locate the client object positioning parameters mLocationClient. SetLocationOption (mLocationOption); / / start positioning mLocationClient startLocation ();Copy the code
And then you parse the AMapLocation object in the callback method of the listener, which contains the address, the city, the county, the street, the region code, the city code, and so on, and you can add a tag there to locate the current location. How do I fix the tag in the center of the screen? Also in this:
/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- this is the position change to monitor -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - @ Override public void onLocationChanged(AMapLocation aMapLocation) { if (aMapLocation ! = null) {if (aMapLocation getErrorCode () = = 0) {/ / analytical aMapLocation can obtain corresponding content. LatLng latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()); If (locationMarker == null) {if (locationMarker == null) {if (locationMarker == null) { LocationMarker = amap.addMarker (new MarkerOptions() .position(latLng).snippet(" fastest 1 minute ").draggable(true).setflat (true)); locationMarker.showInfoWindow(); Indowindow amap.addText (new TextOptions().position(latLng).text(aMapLocation.getAddress())); / / fixed label in the middle of the screen locationMarker setPositionByPixels (mMapView. GetWidth () / 2, mMapView. GetHeight () / 2); } else {/ / has been added, modify location locationMarker. SetPosition (latLng); } / / can then be moved to the anchor point, use animateCamera have animation aMap. AnimateCamera (CameraUpdateFactory. NewLatLngZoom (latLng, 15)); Latitude and longitude 2. Zoom level}else {// If the location fails, you can determine the cause of the failure by ErrCode. ErrInfo is an error message, for details, see the error code table. Log.e("AmapError","location Error, ErrCode:" +aMapLocation.getErrorCode() + ", errInfo:"+ aMapLocation.getErrorInfo()); }}}Copy the code
The second way to implement OnMapLoadedListener is to add a marker in the center of the map in the callback method, and then encapsulate a method to enable a single location:
aMap.setOnMapLoadedListener(this);Copy the code
/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- OnMapLoaded map is loaded when the callback this method -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- @ Override public void onMapLoaded() { MarkerOptions markerOptions = new MarkerOptions(); markerOptions.setFlat(true); MarkerOptions. Anchor (0.5 0.5 f, f); markerOptions.position(new LatLng(0, 0)); Markeroptions.snippet (" soonest 1 minute ").draggable(true).setflat (true); markerOptions.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_loaction_start))); mPositionMark = aMap.addMarker(markerOptions); mPositionMark.showInfoWindow(); / / active display indowindow mPositionMark. SetPositionByPixels (mMapView. GetWidth () / 2, mMapView. GetHeight () / 2); mLocationTask.startSingleLocate(); }Copy the code
The encapsulation of the single positioning method is here, very simple:
Public void startSingleLocate() {AMapLocationClientOption =new AMapLocationClientOption(); option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy); option.setOnceLocation(true); mLocationClient.setLocationOption(option); mLocationClient.startLocation(); }Copy the code
It’s time to post an illustration:
Yes, it’s ugly
How do you make buttons hover on the map? It’s easy, too
Copy the code
Copy the code
Geocoding + reverse geocoding
Let’s talk about geocoding (address to coordinate)/ inverse geocoding (coordinate to address) function, still very simple, once again mention autonavi human documents! Steps to realize address transfer coordinates:
// Construct the GeocodeSearch object and set the listener. geocodeSearch = new GeocodeSearch(this); geocodeSearch.setOnGeocodeSearchListener(this); GeocodeQuery = GeocodeQuery = GeocodeQuery = GeocodeQuery = GeocodeQuery = getFromLocationNameAsyn GeocodeQuery = newGeocodeQuery(address, "010"); GeocodeQuery = newGeocodeQuery(address, "010"); geocoderSearch.getFromLocationNameAsyn(query);Copy the code
Coordinate transfer address implementation steps:
oderSearch = new GeocodeSearch(this); geocoderSearch.setOnGeocodeSearchListener(this); // Same as above // The first parameter indicates a Latlng(latitude and longitude), the second parameter indicates the range of meters, RegeocodeQuery Query = newRegeocodeQuery(latLonPoint, 200, geocodesearch.amap); geocoderSearch.getFromLocationAsyn(query);Copy the code
Call ();
/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - coordinate transfer address/coordinate listening in the callback -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / result with the result you want. @ Override public void onRegeocodeSearched(RegeocodeResult result, int rCode) { result.getGeocodeAddressList().get(0).getLatLonPoint(); } @Override public void onGeocodeSearched(GeocodeResult result, int rCode) { result.getRegeocodeAddress().getFormatAddress(); }Copy the code
5. Enter prompt +Poi search
Finally, the search tip +Poi search function:
Poi search
Implementation steps:
There are already two encapsulated classes, one for input hints and one for Poi search
import android.content.Context; import android.util.Log; import com.amap.api.services.core.AMapException; import com.amap.api.services.help.Inputtips; import com.amap.api.services.help.Inputtips.InputtipsListener; import com.amap.api.services.help.Tip; import java.util.ArrayList; import java.util.List; /** * ClassName:InputTipTask
* Function: A search service that simply encapsulates Inputtips, * @author yiyi. Qi * @version * @since JDK 1.6 * @see */ public class InputTipTask implements InputtipsListener { private static InputTipTask mInputTipTask; private Inputtips mInputTips; private RecomandAdapter mAdapter; Context mContext; public static InputTipTask getInstance(Context context, RecomandAdapter adapter){ if(mInputTipTask==null){ mInputTipTask=new InputTipTask(context); } / / singleton, repeatedly enter DestinationActivity incoming RecomandAdapter object is not the same. MInputTipTask setRecommandAdapter (adapter); return mInputTipTask; } public void setRecommandAdapter(RecomandAdapter adapter){ mAdapter=adapter; } private InputTipTask(Context context ){ mInputTips=new Inputtips(context, this); } public void searchTips(String keyWord, String city){ try { mInputTips.requestInputtips(keyWord, city); } catch (AMapException e) { e.printStackTrace(); } } @Override public void onGetInputtips(List tips, If (resultCode==1000&&tips) {//v3.2.1 and later SDK return code 1000 is normal do not pay attention to if(resultCode==1000&&tips! =null){ ArrayList positions=new ArrayList(); For (Tip Tip :tips){// Address city(adcode) positions. Add (new PositionEntity(0, 0, tip.getName(), tip.getAdCode ())); } mAdapter.setPositionEntities(positions); mAdapter.notifyDataSetChanged(); PoiSearchTask poiSearchTask=new PoiSearchTask(mContext.getApplicationContext(), mAdapter); for(int i = 0; iCopy the code
import android.content.Context; import com.amap.api.services.core.PoiItem; import com.amap.api.services.poisearch.PoiResult; import com.amap.api.services.poisearch.PoiSearch; import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener; import com.amap.api.services.poisearch.PoiSearch.Query; import java.util.ArrayList; import java.util.List; /** * ClassName:PoiSearchTask
* Function: simple encapsulation of POI search functions, and the results are displayed for use with shameshameAdapter
* @author yiyi.qi * @version * @since JDK 1.6 * @see */ public class PoiSearchTask implements OnPoiSearchListener { private Context mContext; private RecomandAdapter mRecommandAdapter; public PoiSearchTask(Context context, RecomandAdapter recomandAdapter) { mContext = context; mRecommandAdapter = recomandAdapter; } public void search(String keyWord, String city) { Query query = new PoiSearch.Query(keyWord, "", city); query.setPageSize(10); query.setPageNum(0); PoiSearch poiSearch = new PoiSearch(mContext, query); poiSearch.setOnPoiSearchListener(this); poiSearch.searchPOIAsyn(); } @Override public void onPoiSearched(PoiResult poiResult, int resultCode) { if (resultCode == 1000 && poiResult ! = null) { ArrayList pois=poiResult.getPois(); if(pois==null){ return; } List entities=new ArrayList(); for(PoiItem poiItem:pois){ PositionEntity entity=new PositionEntity(poiItem.getLatLonPoint().getLatitude(), poiItem.getLatLonPoint().getLongitude(), poiItem.getTitle(),poiItem.getCityName()); entities.add(entity); } mRecommandAdapter.setPositionEntities(entities); mRecommandAdapter.notifyDataSetChanged(); Override public void onpoiitemsearchable (PoiItem, int I) {}Copy the code
All you need to do is copy this class into your project and then implement the TextWatcher interface in the search Activity and make the following call:
@override public void onTextChanged(CharSequence s, int start, int before, int count) { if (RouteTask.getInstance(getApplicationContext()).getStartPoint() == null) { Toast.maketext (getApplicationContext(), "check network, Key, etc. ", toast.length_short).show(); return; } InputTipTask.getInstance(getApplicationContext(), mRecomandAdapter).searchTips(s.toString(), RouteTask.getInstance(getApplicationContext()).getStartPoint().city); }Copy the code
If you want to click for a more detailed Poi search, just call from the appropriate location:
PoiSearchTask poiSearchTask=new poiSearchTask (getApplicationContext(),mRecomandAdapter); // Start a POI search poiSearchTask.search(mDestinaionText.getText().toString(),RouteTask.getInstance(getApplicationContext()).getStartPoint() .city);Copy the code
The above entity Bean requires a location:
/**
* ClassName:PositionEntity
* Function: encapsulates the location entity
Public class PositionEntity {@override public String toString(); { return "PositionEntity{" + "latitue=" + latitue + ", longitude=" + longitude + ", address='" + address + '\'' + ", city='" + city + '\'' + '}'; } public double latitue; public double longitude; public String address; public String city; public PositionEntity() {} public PositionEntity(double latitude, double longtitude, String address, String city) { this.latitue = latitude; this.longitude = longtitude; this.address = address; this.city = city; }}Copy the code
After will bring navigation related articles, if where do not understand or write the wrong place can contact me! Please forgive me for my shortcomings! Thanks for Posting a last address, if useful to aggregation Marker can be sent to this, very detailed:
Lbsbbs.amap.com/forum.php?m...