Android Baidu Map location to obtain the surrounding location of the implementation code _android

Source: Internet
Author: User

This article explains the Android Baidu map positioning to obtain the surrounding location of the code to share for everyone's reference, the specific contents are as follows

Effect Chart:

Specific code:

1. 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=" match_parent "android:layout_height=" Ma Tch_parent "> <relativelayout android:layout_width=" match_parent "android:layout_height=" @dimen/height_ 
        Top_bar "android:background=" @color/common_top_bar_dark "android:gravity=" center_vertical "> <Button Android:id= "@+id/btn_location_back" android:layout_width= "wrap_content" android:layout_height= "Ma Tch_parent "android:drawableleft=" @drawable/back "android:text=" @string/top_back "style=" @style/BT
        N_title_bar "android:layout_alignparentleft=" true "android:onclick=" Back "/> <textview Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" Android:layout_centerinpa Rent= "true" android:text="@string/location_message" style= "@style/txt_titlebar_message"/> <button android:id= "@+id/btn_ Location_ok "android:layout_width=" 52DP "android:layout_height=" Match_parent "android:layout_align
        Parentright= "true" android:background= "@drawable/common_tab_bg" android:text= "@string/txt_queding" style= "@style/btn_title_bar"/> </RelativeLayout> <com.baidu.mapapi.map.mapview Android:layout_weig ht= "2" android:id= "@+id/mapview_location" android:layout_width= "fill_parent" android:layout_height= "MATC" H_parent "android:clickable=" true "/> <listview android:layout_weight=" 3 "android:id=" @+id/lv_l Ocation_nearby "android:layout_width=" match_parent "android:layout_height=" match_parent "/> </LinearLayo


 Ut>

Layout file is above is a Baidu map of the Mapview, the following is a display of the surrounding location of the ListView, very simple.

1, automatic positioning

Let's take a look at our location to achieve our position
1. Initialize the component to be used first

 /**
   * Initialization component *
   /
  private void Initview () {
    btnlocationback = (Button) Findviewbyid (r.id.btn_location_ back);
    Btnlocationback.setonclicklistener (this);
    Btnlocationok = (Button) Findviewbyid (R.ID.BTN_LOCATION_OK);
    Btnlocationok.setonclicklistener (this);
    Mapviewlocation = (Mapview) Findviewbyid (r.id.mapview_location);
    Lvlocnear = (ListView) Findviewbyid (R.id.lv_location_nearby);
    Nearlist = new arraylist<poiinfo> ();
    adapter = new Locnearaddressadapter (context, nearlist, isselected);
    Lvlocnear.setadapter (adapter);
  }

2. Initialize the Locationclient class, which needs to be declared in the main thread

Public locationclient mlocationclient = null;
Public Bdlocationlistener MyListener = new Mylocationlistener ();

public void OnCreate () {
  mlocationclient = new Locationclient (Getapplicationcontext ());   DECLARE locationclient class
  Mlocationclient.registerlocationlistener (MyListener);  Registering the Listener function
}

3. Configure Location SDK Parameters
set positioning parameters include: Positioning mode (high-precision positioning mode, low-power positioning mode and only device positioning mode), return the type of coordinates, whether to open the GPS, whether to return address information, location semantic information, POI information and so on.
Locationclientoption class, which is used to set the location of the Location SDK

private void Initlocation () {locationclientoption option = new Locationclientoption (); Option.setlocationmode (locationmode.hight_accuracy)/optional, default high-precision, set positioning mode, High-precision, low-power, only equipment Option.setcoortype ("Bd09ll")
    ;//optional, default GCJ02, set the returned positioning result coordinate system int span=1000; Option.setscanspan (span);//optional, default 0, that is, positioning only once, setting the interval required to initiate a location request is greater than or equal to 1000ms is valid option.setisneedaddress (true);/optional, Set whether address information is required, default does not require OPTION.SETOPENGPS (true);//optional, default false, set whether to use GPS option.setlocationnotify (TRUE);//optional, default false, Set whether the GPS result Option.setisneedlocationdescribe (true) if the GPS is in effect, and/or optional, default false, and whether the location semantic result is required, can be obtained in bdlocation.getlocationdescribe, the result is similar to "near Beijing Tian an door" option.setisneedlocationpoilist (true);/optional, default false, Set whether the POI result is required, you can get Option.setignorekillprocess (false) in bdlocation.getpoilist;//optional, default false, locate the SDK inside is a service, and put it in the standalone process, set whether to kill the process at stop, and kill option by default. Setignorecacheexception (false);//optional, default false, set whether to collect crash information, default collection Option.setenablesimulategps (FALSE),//optional, default false, Set whether to filter GPS simulation results, the default need Mlocationclient.setlocoption (option);
 }

4. Implementing the Bdlocationlistener Interface

 /** * Listener function, when there is a new location, formatted into a string, output to the screen/public class Mylocationlistenner implements Bdlocationlistener {@Overr
      IDE public void Onreceivelocation (bdlocation location) {if (location = = null) {return;
      } log.d ("Map", "On Location Change Received:" + location);
      LOG.D ("Map", "addr:" + location.getaddrstr ());
      if (ProgressDialog!= null) {Progressdialog.dismiss (); } if (lastlocation!= null) {if (lastlocation.getlatitude () = = Location.getlatitude () && Lastlocat
          Ion.getlongitude () = = Location.getlongitude ()) {LOG.D ("map", "same location, skip Refresh"); Mmapview.refresh ();
          Need this refresh?
        Return
      } lastlocation = location;
      Mbaidumap.clear ();
      Mcurrentlantitude = Lastlocation.getlatitude ();
      Mcurrentlongitude = Lastlocation.getlongitude ();
LOG.E (">>>>>>>", Mcurrentlantitude + "," + mcurrentlongitude);      LATLNG LlA = new Latlng (Lastlocation.getlatitude (), Lastlocation.getlongitude ());
      Coordinateconverter converter = new Coordinateconverter ();
      Converter.coord (LlA);
      Converter.from (CoordinateConverter.CoordType.COMMON);
      LATLNG convertlatlng = Converter.convert (); Overlayoptions OoA = new markeroptions (). Position (CONVERTLATLNG). Icon (bitmapdescriptorfactory. Fromresource (R.dr
      Awable.icon_marka)). ZIndex (4). Draggable (True);
      Mcurrentmarker = (Marker) mbaidumap.addoverlay (OoA);
      Mapstatusupdate u = mapstatusupdatefactory.newlatlngzoom (convertlatlng, 16.0f);
      Mbaidumap.animatemapstatus (U);
        New Thread (New Runnable () {@Override public void run () {searchneayby ();
    }). Start ();
      public void Onreceivepoi (Bdlocation poilocation) {if (poilocation = = null) {return;

 }
    }
  }

There are many parameters in the bdlocation received here, I believe there is always a useful to you.

2, according to the latitude and longitude of positioning

This method does not require automatic positioning, is based on the latitude and longitude to show the location of the map

 *
  * Show latitude and longitude position
  *
  /private void Showmap (double latitude, double longtitude, String address) {
//    Sendbutton.setvisibility (view.gone);
    LATLNG LlA = new Latlng (latitude, longtitude);
    Coordinateconverter converter = new Coordinateconverter ();
    Converter.coord (LlA);
    Converter.from (CoordinateConverter.CoordType.COMMON);
    LATLNG convertlatlng = Converter.convert ();
    Overlayoptions OoA = new markeroptions (). Position (CONVERTLATLNG). Icon (Bitmapdescriptorfactory.fromresource ( R.drawable.icon_marka))
        . ZIndex (4). Draggable (true);
    Markera = (Marker) (Mbaidumap.addoverlay (OoA));
    U = mapstatusupdatefactory.newlatlngzoom (convertlatlng, 16.0f);
    Mbaidumap.animatemapstatus (u);
    New Thread (New Runnable () {
      @Override public
      void Run () {
        searchneayby ();
      }
    }). Start ();
  }

3, access to the surrounding location

Finally look at how to get the location of the perimeter, here need to use a class poinearbysearchoption in the SDK, we can look at the class reference:

    • poinearbysearchoption keyword (java.lang.String key)
    • Retrieving keywords
    • Poinearbysearchoption location (latlng location)
    • Retrieve location
    • Poinearbysearchoption pagecapacity (int pagecapacity)
    • Set per page capacity, default to 10 per page
    • Poinearbysearchoption pagenum (int pagenum)
    • Paging number
    • Poinearbysearchoption radius (int radius)
    • Set the radius of the search
    • Poinearbysearchoption SortType (Poisorttype sorttype)
    • Search results collation, optional, default

Here are some of its methods, and we can see that we just need to set the keyword, the perimeter radius, the location of the search, the collation, the page number, the number of pages per page, and so on. Then we implement ongetpoisearchresultlistener this interface to obtain the surrounding geographical results.

/** * Search around the location * * private void Searchneayby () {poinearbysearchoption option = new Poinearbysearchoption ();
    Option.keyword ("office building");
    Option.sorttype (Poisorttype.distance_from_near_to_far);
    Option.location (New Latlng (Mcurrentlantitude, mcurrentlongitude));
    if (RADIUS!= 0) {Option.radius (RADIUS);
    else {Option.radius (1000);
    } option.pagecapacity (20);

  Mpoisearch.searchnearby (option); * * * Accept the perimeter location result * @param poiresult/@Override public void Ongetpoiresult (Poiresult poiresult) {if Poiresul T!= null) {if (Poiresult.getallpoi ()!=null&&poiresult.getallpoi (). Size () >0) {Nearlist.addall (PO
        Iresult.getallpoi ());
            if (nearlist!= null && nearlist.size () > 0) {for (int i = 0; i < nearlist.size (); i++) {
          Isselected.put (I, false);
        } Message msg = new Message ();
        Msg.what = 0;
      Handler.sendmessage (msg);

  }  }
  }

 

After getting the data, update the adapter to show the surrounding position OK, and finally realize a small function, that is, click each position in the list, show the location of the small icon according to the change in location

 /**
     * Peripheral Location List Click event
    /Lvlocnear.setonitemclicklistener (new Adapterview.onitemclicklistener () {
      @ Override public
      void Onitemclick (adapterview<?> adapterview, view view, int I, long l) {
        Adapter.setselected (i);
        Adapter.notifydatasetchanged ();
        Poiinfo ad = (poiinfo) adapter.getitem (i);
        U = mapstatusupdatefactory.newlatlng (ad.location);
        Mbaidumap.animatemapstatus (u);
        if (!isloc) {
          mcurrentmarker.setposition (ad.location);
        } else {
          markera.setposition (ad.location);
        }
      }
    });

OK, very simple and useful a small function, will give users a very good experience effect.

I hope you will enjoy this 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.