[Baidu map development 4] implementation of basic Baidu map operations

Source: Internet
Author: User
Tags call back

Preface:

[Baidu map development 4] Baidu map basic operation functions to explain (blog address: http://blog.csdn.net/developer_jiangqq), reprint please note.

Author: hmjiangqq

Email: jiangqqlmj@163.com

In the previous article, we learned about [Baidu map development 3] Baidu map UI control function (click to jump). Today, we will continue to look at the implementation of some basic operation functions of Baidu map;

(1) Basic Introduction:

Some basic operations and control of Baidu map include map scaling, rotation, overlooking, single-click, long-press, and other control events. To implement the preceding three functions, MapController class and single-click, mapView's listening event processing interface MKMapTouchListener is used for long-press events.

(2) control class, interface Basic Introduction 1: MapController: Map Operation Controller. Today we mainly use the following methods:

①: Public float setZoom (float zoomLevel): sets the zoom level of the map. The value range is [3, 19].

②: Public void setRotation (int rotate): sets the Rotation Angle of the map.

③: Public void setOverlooking (int voidlook): sets the view angle of a map.

2: MKMapTouchListener: the map Click Event listener interface. The main methods are as follows:

①: Void onMapClick (GeoPoint point): Click an event on the map and call back the coordinates of the clicked map.

②: Void onMapDoubleClick (GeoPoint point): double-click the map event, and calls back the coordinates of the double-click map.

③: Void onMapLongClick (GeoPoint point): Specifies the coordinates of the long-pressed map.

(3) how to use the event listener:

You only need to register the MKMapTouchListener listener in the MapView object, click it, double-click it, and long-Press the event method. The implementation method is as follows:

/*** Set the map Click Event listener */mapTouchListener = new MKMapTouchListener () {@ Overridepublic void onMapClick (GeoPoint point) {touchType = "click"; currentPt = point; updateMapState () ;}@ Overridepublic void onMapDoubleClick (GeoPoint point) {touchType = "double-click"; currentPt = point; updateMapState () ;}@ Overridepublic void onMapLongClick (GeoPoint point) {touchType = "Long press"; currentPt = point; updateMapState () ;}}; // register the mMapView event for the map. regMapTouchListner (mapTouchListener );
(4) let's take a look at the demo example in Baidu map SDK (the comments in the Code have been added in detail on this basis)

1: MyApplication. java: Set BMapManager global variables and verify the key. The Code is as follows:

Package com. ztt. baidumap. ui; import android. app. application; import android. content. context; import android. util. log; import android. widget. toast; import com. baidu. mapapi. BMapManager; import com. baidu. mapapi. MKGeneralListener; import com. baidu. mapapi. map. MKEvent;/*** Custom Application for key identification and verification (using a singleton) * @ author Jiangqq * @ time 2014/03/15 */public class MyApplication extends Application {public static MyApplication instance = null; BMapManager mBMapManager = null; public boolean m_bKeyRight = true; public static final String strKey = "vUAGbPwLpolIqiwWisnQPeIE"; // public static MyApplication getInstance () applied for on the Baidu map Official Website () {return instance;} @ Overridepublic void onCreate () {super. onCreate (); instance = this; // initialize and verify the initEngineManager (this) when the APP starts );} /*** verify key * @ param pContext */private void initEngineM Anager (Context pContext) {if (mBMapManager = null) {mBMapManager = new BMapManager (pContext);} if (! MBMapManager. init (strKey, new MyGeneralListener () {Toast. makeText (MyApplication. getInstance (), "BMapManager initialization error! ", Toast. LENGTH_LONG ). show () ;}// common event listening, used to handle common network errors, authorization verification errors, and other static class MyGeneralListener implements MKGeneralListener {@ Override public void onGetNetworkState (int iError) {if (iError = MKEvent. ERROR_NETWORK_CONNECT) {Toast. makeText (MyApplication. getInstance (), "your network has an error! ", Toast. LENGTH_LONG). show ();} else if (iError = MKEvent. ERROR_NETWORK_DATA) {Toast. makeText (MyApplication. getInstance ()," enter the correct search conditions! ", Toast. LENGTH_LONG ). show ();} else {Log. d ("zttjiangqq", "iError =" + iError );}//...} @ Override public void onGetPermissionState (int iError) {// a non-zero value indicates that the key verification fails if (iError! = 0) {// Authorization Key error: Toast. makeText (MyApplication. getInstance (), "Please go to DemoApplication. enter the correct authorization Key in the java file and check whether your network connection is normal! Error: "+ iError, Toast. LENGTH_LONG ). show (); MyApplication. getInstance (). m_bKeyRight = false;} else {MyApplication. getInstance (). m_bKeyRight = true; Toast. makeText (MyApplication. getInstance (), "key Authentication successful", Toast. LENGTH_LONG ). show ();}}}}
2: Layout file:

<? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: orientation = "vertical" android: layout_width = "fill_parent" android: layout_height = "fill_parent"> <LinearLayout android: orientation = "horizontal" android: layout_width = "fill_parent" android: layout_height = "50dip"> <Button android: id = "@ + id/zoombutton" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: layout_weight = "1" android: background = "@ drawable/button_style" android: text = "zoom"/> <EditText android: id = "@ + id/zoomlevel" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: layout_weight = "1" android: text = "10"/> <Button android: id = "@ + id/rotatebutton" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: layout_weight = "1" android: background = "@ drawable/button_style" android: text = "Rotate"/> <EditText android: id = "@ + id/rotateangle" android: text = "90" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: layout_weight = "1"/> <Button android: id = "@ + id/overlookbutton" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: layout_weight = "1" android: background = "@ drawable/button_style" android: text = "overlooking"/> <EditText android: id = "@ + id/overlookangle" android: text = "-30" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: layout_weight = "1"/> </LinearLayout> <TextView android: id = "@ + id/state" android: text = "click, long press, and double-click a map to get the longitude and latitude and MAP status" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: lines = "3"/> <RelativeLayout android: orientation = "vertical" android: layout_width = "fill_parent" android: layout_height = "fill_parent"> <com. baidu. mapapi. map. mapView android: id = "@ + id/bmapView" android: layout_width = "fill_parent" android: layout_height = "fill_parent" android: clickable = "true"/> <Button android: id = "@ + id/savescreen" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_alignParentTop = "true" android: layout_alignParentRight = "true" android: layout_marginTop = "10dip" android: background = "@ drawable/button_style" android: text = ""/> </RelativeLayout> </LinearLayout>
3: function implementation Activity code:

Package com. ztt. baidumap. ui; import java. io. file; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. IOException; import android. app. activity; import android. graphics. bitmap; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. editText; import android. widget. textView; import android. w Idget. toast; import com. baidu. mapapi. BMapManager; import com. baidu. mapapi. map. MKMapTouchListener; import com. baidu. mapapi. map. MKMapViewListener; import com. baidu. mapapi. map. mapController; import com. baidu. mapapi. map. mapPoi; import com. baidu. mapapi. map. mapView; import com. baidu. platform. comapi. basestruct. geoPoint;/*** demonstrate map scaling, rotation, and view control */public class MapControlDemo extends Activity {/*** MapView is the main map control */p Rivate MapView mMapView = null;/*** map control using MapController */private MapController mMapController = null;/*** MKMapViewListener is used to process map Event Callback */MKMapViewListener mMapListener = null; /*** capture screen coordinates */MKMapTouchListener mapTouchListener = null;/*** click the current vertex */private GeoPoint currentPt = null; /*** control Button */private Button zoomButton = null; // scale private Button rotateButton = null; // rotate private Button overl OokButton = null; // overlooking private Button saveScreenButton = null; // *****/private String touchType = null; /*** panel used to display the MAP status */private TextView mStateBar = null; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState);/*** before using the map sdk, initialize BMapManager. * BMapManager is global and can be shared by multiple mapviews. It needs to be created before the map module is created. * If the map module is still in use, BMapManager should not destroy */MyApplication app = (MyApplication) this. getApplication (); if (app. mBMapManager = null) {app. mBMapManager = new BMapManager (getApplicationContext ();/*** initialize BMapManager */app if BMapManager is not initialized. mBMapManager. init (MyApplication. strKey, new MyApplication. myGeneralListener ();}/*** because MapView is initialized in setContentView (), it must be */setContentView (R. layout. activity_mapcontrol); mMapView = (MapView) findViewByI D (R. id. bmapView);/*** get map controller */mMapController = mMapView. getController ();/*** sets whether the map responds to the click event. */mMapController. enableClick (true);/*** set the map zoom level */mMapController. setZoom (12); mStateBar = (TextView) findViewById (R. id. state);/*** initialize the map event listener */initListener ();/*** move the map to Tiananmen * use Baidu longitude and latitude coordinates, you can use http://api.map.baidu.com/lbsapi/getpoint/index.htmlto query geographic coordinates * if you need to display the location of other coordinate systems on baidu map, please send an email to mapapi @ baidu. Com application coordinate conversion interface */double cLat = 39.945; double cLon = 116.404; GeoPoint p = new GeoPoint (int) (cLat * 1E6), (int) (cLon * 1E6); mMapController. setCenter (p);}/*** add listener event */private void initListener () {/*** set map Click Event listener */mapTouchListener = new MKMapTouchListener () {@ Overridepublic void onMapClick (GeoPoint point) {touchType = "click"; currentPt = point; updateMapState () ;}@ Overridepublic void onMapDoub LeClick (GeoPoint point) {touchType = "double-click"; currentPt = point; updateMapState () ;}@ Overridepublic void onMapLongClick (GeoPoint point) {touchType = "Long press"; currentPt = point; updateMapState () ;}}; // register the mMapView event for the map. regMapTouchListner (mapTouchListener);/*** set map event listening */mMapListener = new MKMapViewListener () {@ Overridepublic void onMapMoveFinish () {/*** callback for Processing Map movement completed here * after scaling and translation operations are completed, this callback is triggered */updateMapState () ;}@ Overridepublic void onClickMapPoi (MapPoi mapPoiInfo) {/*** process the basemap poi click event here * display the basemap poi name and move it to this point * set: mMapController. enableClick (true); this callback can be triggered **/} @ Overridepublic void onGetCurrentMap (Bitmap B) {/*** when mMapView is called. after getCurrentMap (), this callback will be triggered * can be saved to the storage device */File file = new File ("/mnt/sdcard/test.png"); FileOutputStream out; try {out = new FileOutputStream (file); if (B. compress (Bitmap. compressFor Mat. PNG, 70, out) {out. flush (); out. close ();} Toast. makeText (MapControlDemo. this, "screen succeeded, image exists:" + file. toString (), Toast. LENGTH_SHORT ). show ();} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace () ;}@ Overridepublic void onMapAnimationFinish () {/*** after the map completes the animation-carrying operation (for example, animationTo, this callback is triggered */updateMapState () ;}@ Overridepublic void onMapLoadFinish (){ // TODO Auto-generated method stub }}; mMapView. regMapViewListener (MyApplication. getInstance (). mBMapManager, mMapListener);/*** set the Button listener */zoomButton = (Button) findViewById (R. id. zoombutton); rotateButton = (Button) findViewById (R. id. rotatebutton); overlookButton = (Button) findViewById (R. id. overlookbutton); saveScreenButton = (Button) findViewById (R. id. savescreen); OnClickListener onClickListener = new OnCl IckListener () {@ Overridepublic void onClick (View view) {if (view. equals (zoomButton) {perfomZoom ();} else if (view. equals (rotateButton) {perfomRotate ();} else if (view. equals (overlookButton) {perfomOverlook ();} else if (view. equals (saveScreenButton) {//, save the image mMapView in MKMapViewListener. getCurrentMap (); Toast. makeText (MapControlDemo. this, "screenshots... ", Toast. LENGTH_SHORT ). show () ;}updatemapstate ();} }; ZoomButton. setOnClickListener (onClickListener); rotateButton. setOnClickListener (onClickListener); overlookButton. setOnClickListener (onClickListener); saveScreenButton. setOnClickListener (onClickListener);}/*** process scaling * sdk scaling level range: [3.0, 19.0] */private void perfomZoom () {EditText t = (EditText) findViewById (R. id. zoomlevel); try {float zoomLevel = Float. parseFloat (t. getText (). toString (); // sets the map zoom level MMapController. setZoom (zoomLevel);} catch (NumberFormatException e) {Toast. makeText (this, "enter the correct zoom level", Toast. LENGTH_SHORT ). show () ;}/ *** handle rotation * Rotation Angle Range:-180 ~ 180, unit: degrees counter-clockwise rotation */private void perfomRotate () {EditText t = (EditText) findViewById (R. id. rotateangle); try {int rotateAngle = Integer. parseInt (t. getText (). toString (); // sets the map Rotation Angle mMapController. setRotation (rotateAngle);} catch (NumberFormatException e) {Toast. makeText (this, "enter the correct Rotation Angle", Toast. LENGTH_SHORT ). show () ;}/ *** process the top-down list *. The top-down range is-45 ~ 0, unit: Degree */private void perfomOverlook () {EditText t = (EditText) findViewById (R. id. overlookangle); try {int overlookAngle = Integer. parseInt (t. getText (). toString (); // you can specify a map to look down at mMapController. setOverlooking (overlookAngle);} catch (NumberFormatException e) {Toast. makeText (this, "enter the correct corner", Toast. LENGTH_SHORT ). show () ;}/ *** update MAP status display panel */private void updateMapState () {if (mStateBar = null) {return;} String state = ""; if (currentPt = null) {state = "click, long press, double-click map to get latitude and longitude and MAP status";} else {state = String. format (touchType + ", current longitude: % f current latitude: % f", currentPt. getLongitudeE6 () * 1E-6, currentPt. getLatitudeE6 () * 1E-6);} state + = "\ n"; state + = String. format ("zoom level = %. 1f rotate angle = % d overlaylook angle = % d ", mMapView. getZoomLevel (), mMapView. getMapRotation (), mMapView. getMapOverlooking (); mStateBar. setText (state) ;}@ Override protected void onPause () {/*** the life cycle of MapView is synchronized with the Activity. MapView must be called when the activity is suspended. onPause () */mMapView. onPause (); super. onPause () ;}@ Override protected void onResume () {/*** the life cycle of MapView is synchronized with the Activity. When the activity is restored, MapView must be called. onResume () */mMapView. onResume (); super. onResume () ;}@ Override protected void onDestroy () {/*** the life cycle of MapView is synchronized with the Activity. When the activity is destroyed, MapView must be called. destroy () */mMapView. destroy (); super. onDestroy () ;}@ Override protected void onSaveInstanceState (Bundle outState) {super. onSaveInstanceState (outState); mMapView. onSaveInstanceState (outState) ;}@ Override protected void onRestoreInstanceState (Bundle savedInstanceState) {super. onRestoreInstanceState (savedInstanceState); mMapView. onRestoreInstanceState (savedInstanceState );}}
4: run:



[Note] the configuration of AndroidManifest. xml is the same as that in the previous article.

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.