English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Example Code for Location and Destination Navigation in Android

Today, I accidentally saw a technical master using Baidu Map for location and destination navigation Demo. It's very good, so I转载过来 share together, let's see the implementation effect below:

       

After entering, you will first get the current location, which will be displayed on the map. After entering the destination in the input box, the optimal route will appear on the map. Here, I have set it to the driving route with the shortest distance. There are also bus routes and walking routes, with detailed comments in the code. In addition, information about each node on the route, as well as the distance from the starting point and destination, is output in the console. The information displayed is the navigation information at the current node. As shown in the following figure:

 

Next, let's see how to implement it. First, register a Baidu developer account and enter the Baidu Map API to view relevant materials such as Baidu Map API. Then, register an APP KEY for the application that needs to be added to the map. After registration, download the Baidu Map jar file, create a new project, and import it. Below is the specific code implementation, with detailed comments in the code:

public class NavigationDemoActivity extends MapActivity { 
  private String mMapKey = "register your own key"; 
  private EditText destinationEditText = null; 
  private Button startNaviButton = null; 
  private MapView mapView = null; 
  private BMapManager mMapManager = null; 
  private MyLocationOverlay myLocationOverlay = null; 
  //Register this listener when onResume, and remove it when onPause, note that this listener is not Android's built-in, it is from Baidu API 
  private LocationListener locationListener; 
  private MKSearch searchModel; 
  GeoPoint pt; 
  @Override 
  public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    setContentView(R.layout.main); 
    destinationEditText = (EditText) this.findViewById(R.id.et_destination); 
    startNaviButton = (Button) this.findViewById(R.id.btn_navi); 
    mMapManager = new BMapManager(getApplication()); 
    mMapManager.init(mMapKey, new MyGeneralListener()); 
    super.initMapActivity(mMapManager); 
    mapView = (MapView) this.findViewById(R.id.bmapsView); 
    //Enable built-in zoom controls 
    mapView.setBuiltInZoomControls(true);  
    //Set overlay display during zoom animation, default is not to draw 
//    mapView.setDrawOverlayWhenZooming(true); 
    //Get the current location layer 
    myLocationOverlay = new MyLocationOverlay(this, mapView); 
    //Add the layer of the current location to the bottom layer of the map 
    mapView.getOverlays().add(myLocationOverlay); 
    // Register location event 
    locationListener = new LocationListener(){ 
      @Override 
      public void onLocationChanged(Location location) { 
        if (location != null){ 
          //Generate GEO type coordinates and locate the location marked by the coordinate on the map 
           pt = new GeoPoint((int)(location.getLatitude()*1e6), 
              (int)(location.getLongitude()*1e6))(); 
//         System.out.println("---"+location.getLatitude() +: "+location.getLongitude()); 
          mapView.getController().animateTo(pt); 
        } 
      } 
    }; 
    //Initialize the search module 
    searchModel = new MKSearch(); 
    //Set the route strategy to the shortest distance 
    searchModel.setDrivingPolicy(MKSearch.ECAR_DIS_FIRST); 
    searchModel.init(mMapManager, new MKSearchListener() { 
      //Callback method for getting driving route 
      @Override 
      public void onGetDrivingRouteResult(MKDrivingRouteResult res, int error) { 
        // Error codes can be referred to the definitions in MKEvent. 
        if (error != 0 || res == null) { 
          Toast.makeText(NavigationDemoActivity.this, "Sorry, no results found", Toast.LENGTH_SHORT).show(); 
          return; 
        } 
        RouteOverlay routeOverlay = new RouteOverlay(NavigationDemoActivity.this, mapView); 
        // This only displays one plan as an example 
        MKRoute route = res.getPlan(0).getRoute(0); 
        int distanceM = route.getDistance(); 
        String distanceKm = String.valueOf(distanceM / 1000) +.+String.valueOf(distanceM % 1000); 
        System.out.println("Distance: "+distanceKm+kilometers---Number of nodes: "+route.getNumSteps()); 
        for (int i = 0; i < route.getNumSteps(); i++) { 
          MKStep step = route.getStep(i); 
          System.out.println("Node information: "+step.getContent()); 
        } 
        routeOverlay.setData(route); 
        mapView.getOverlays().clear(); 
        mapView.getOverlays().add(routeOverlay); 
        mapView.invalidate(); 
        mapView.getController().animateTo(res.getStart().pt); 
      } 
      //The following two methods are the same as the driving plan implementation above 
      @Override 
      public void onGetWalkingRouteResult(MKWalkingRouteResult res, int error) { 
        //Obtain walking route 
      } 
      @Override 
      public void onGetTransitRouteResult(MKTransitRouteResult arg0, int arg1) { 
        //Obtain bus route information 
      } 
      @Override 
      public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) { 
      } 
      @Override 
      public void onGetAddrResult(MKAddrInfo arg0, int arg1) { 
      } 
      @Override 
      public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) { 
      } 
      @Override 
      public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2) { 
      } 
    }); 
    startNaviButton.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
        String destination = destinationEditText.getText().toString(); 
        //Set starting point (current location) 
        MKPlanNode startNode = new MKPlanNode(); 
        startNode.pt = pt; 
        //Set destination 
        MKPlanNode endNode = new MKPlanNode();  
        endNode.name = destination; 
        //Expand search city 
        String city = getResources().getString(R.string.beijing); 
//       System.out.println("----"+city+"---"+destination+"---"+pt); 
        searchModel.drivingSearch(city, startNode, city, endNode); 
        //Walking route 
//       searchModel.walkingSearch(city, startNode, city, endNode); 
        //Bus route 
//       searchModel.transitSearch(city, startNode, endNode); 
      } 
    }); 
  } 
  @Override 
  protected void onResume() { 
    mMapManager.getLocationManager().requestLocationUpdates(locationListener); 
    myLocationOverlay.enableMyLocation(); 
    myLocationOverlay.enableCompass(); // Turn on the compass 
    mMapManager.start(); 
    super.onResume(); 
  } 
  @Override 
  protected void onPause() { 
    mMapManager.getLocationManager().removeUpdates(locationListener); 
    myLocationOverlay.disableMyLocation();//Display the current location 
    myLocationOverlay.disableCompass(); // Close the compass 
    mMapManager.stop(); 
    super.onPause(); 
  } 
  @Override 
  protected boolean isRouteDisplayed() { 
    // TODO Auto-generated method stub 
    return false; 
  } 
  // Common event listener, used to handle common network errors, authorization verification errors, etc. 
  class MyGeneralListener implements MKGeneralListener { 
      @Override 
      public void onGetNetworkState(int iError) { 
        Log.d("MyGeneralListener", "onGetNetworkState error is ")+ iError); 
        Toast.makeText(NavigationDemoActivity.this, "Your network is down!", 
            Toast.LENGTH_LONG).show(); 
      } 
      @Override 
      public void onGetPermissionState(int iError) { 
        Log.d("MyGeneralListener", "onGetPermissionState error is ")+ iError); 
        if (iError == MKEvent.ERROR_PERMISSION_DENIED) { 
          // Authorization Key error: 
          Toast.makeText(NavigationDemoActivity.this,  
              "Please enter the correct authorization Key in the BMapApiDemoApp.java file!", 
              Toast.LENGTH_LONG).show(); 
        } 
      } 
    } 
} 

Then is the layout file:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent" 
  android:orientation="vertical" > 
  <LinearLayout 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" > 
    <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:textSize="18sp" 
      android:text="Destination:" /> 
    <EditText 
      android:id="@"+id/et_destination" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" /> 
  </LinearLayout> 
  <Button  
    android:id="@"+id/btn_navi" 
    android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:text="Start navigate"/> 
  <com.baidu.mapapi.MapView 
    android:id="@"+id/bmapsView" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:clickable="true" /> 
</LinearLayout> 

AndroidMainifest.xml

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
  package="com.ericssonlabs" 
  android:versionCode="1" 
  android:versionName="1.0" > 
  <uses-sdk android:minSdkVersion="8" /> 
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission> 
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission> 
  <uses-permission android:name="android.permission.INTERNET"></uses-permission> 
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> 
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>  
  <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>  
  <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission> 
  <supports-screens android:largeScreens="true" 
    android:normalScreens="true" android:smallScreens="true" 
    android:resizeable="true" android:anyDensity="true"/> 
  <uses-sdk android:minSdkVersion="3></uses-sdk> 
  <application 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" > 
    <activity 
      android:name=".NavigationDemoActivity" 
      android:label="@string/app_name" > 
      <intent-filter> 
        <action android:name="android.intent.action.MAIN"> /> 
        <category android:name="android.intent.category.LAUNCHER"> /> 
      </intent-filter> 
    </activity> 
  </application> 
</manifest> 

That's all the code for implementing Baidu Map positioning and navigation to the destination. I don't know if that's what you want?

That's all for the content of this article. I hope it will be helpful to everyone's learning and that everyone will support the Yelling Tutorial more.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please report any violations by sending an email to codebox.com (replace # with @ when sending an email), and provide relevant evidence. Once verified, this site will immediately delete the infringing content.

You May Also Like