Android maps Application New Vision--mapbox Common function Encapsulation Tool class

Source: Internet
Author: User


previous article- Android Maps application New Horizon--mapbox The initial integration of application development--the multi-platform map framework for global applications is described Mapbox Android -end integration steps,

And the Android map application of the new Horizon--mapbox application development of the simple feature extraction, if you want to know the recommendations first read the top two OH

This article will continue the previous content, the main extraction of common functional packaging tools, can be used directly when the tool class

Direct on Dry Goods

As follows:



public class Mapboxutils {private Mapboxmap mapboxmap;    Private context context; Call the token token of MAPBOXAPI public static String Mapbox_access_token = "    PK.EYJ1IJOIAMFJA3L6IIWIYSI6IMNPB2W3OTLMDDAWNZD1Z20WEG42MJF5DMMIFQ.775C4O6ELT5LA-UUMJJE4W "; Public mapboxutils () {} public mapboxutils (Mapboxmap Mapboxmap, Context context) {This.mapboxmap = Mapboxma        P        This.context = context;    Mapboxmap.setaccesstoken (Mapbox_access_token); /** * Draw the specified picture at the specified location * * @param latitude * @param longitude * @param drawableid the image of the specified ID */PU Blic void Drawmarker (final double latitude, final double longitude, int drawableid) {//Create an Icon object for        The marker to use iconfactory Iconfactory = iconfactory.getinstance (context);        drawable icondrawable = contextcompat.getdrawable (context, Drawableid);        Icon icon = iconfactory.fromdrawable (icondrawable); ADD the custom icon marker to the map mapboxmap.adDmarker (New Markeroptions (). Position (new latlng (latitude, longitude)). Icon). getposit    Ion (); }/** * Draw a simple default tag * * @param latitude * @param longitude * @param title title * @param Sinippe  T description */public void Drawsimplemarker (final double latitude, final double longitude, string title, String sinippet) {//ADD the custom icon marker to the map Mapboxmap.addmarker (new Markeroptions (). Position    (New latlng (latitude, longitude)). Title (title). Snippet (Sinippet));  }/** * Animation jumps to the specified position-specified way * * @param latitude * @param longitude * @param zoom Specify ZOOM * @param BEARING specifies the relative original rotation angle * @param tilt Specify the angle of view */public void jumptolocation (final double latitude, final dou ble longitude, final double zoom, final double bearing, final double tilt) {//Set Target point---Click Back to current position Camerapositi On cameraposition = new Cameraposition.                Builder (). Target (new latlng (latitude, longitude))//sets the center of the map to the specified location        . Zoom (zoom). BEARING (bearing). Tilt (tilt). Build (); Set the user ' s viewpoint as specified in the Cameraposition object Mapboxmap.animatecamera (cameraupdatefactory.ne    Wcameraposition (cameraposition), 3000);  }/** * Animation jumps to the specified position---default */public void Jumptolocationdefault (final double latitude, final double longitude) {//Set Target point---Click Back to current position cameraposition cameraposition = new Cameraposition.builder (). Target (NE                W latlng (latitude, longitude))//sets the center of the map to the specified location. Zoom (11)        . Bearing (0). Tilt (0). build (); Set the user ' s viewpoint as specified in the Cameraposition object Mapboxmap.animatecamera (cameraupdatefactory.ne Wcameraposition (CamerapositiOn), 3000); }/** * Get token token * * @param context * @return */public static String Getmapboxaccesstoken (@Non Null context Context) {try {//Read out androidmanifest packagemanager Packagemanager = con            Text.getpackagemanager (); ApplicationInfo appInfo = Packagemanager. Getapplicationinfo (Context.getpackagename (), PACKAGEMANAGER.G            Et_meta_data);            String token = appInfo.metaData.getString (mapboxconstants.key_meta_data_manifest);            if (token = = NULL | | token.isempty ()) {throw new illegalargumentexception ();        } return token; } catch (Exception e) {//Use fallback on string resource, used for development int TOKENRESID = CO            Ntext.getresources (). Getidentifier ("Mapbox_access_token", "string", Context.getpackagename ()); return Tokenresid! = 0?        Context.getstring (TOKENRESID): null; }    }    /** * This method is to be verified * <p/> * Draw a reference route for the given coordinate points * * @param point */public void Drawmyroute (LATLNG        Point) {//delete all previous tags mapboxmap.removeannotations (); Set the Origin waypoint to the devices location sets the initial position waypoint origin = new Waypoint (Mapboxmap.getmylocation (). g        Etlongitude (), Mapboxmap.getmylocation (). Getlatitude ());        Set destination Path--click the location point waypoint destination = new Waypoint (Point.getlongitude (), Point.getlatitude ()); ADD marker to the destination waypoint Mapboxmap.addmarker (new Markeroptions (). Position (New Latl        Ng (Point)). Title ("Destination"). Snippet ("My destination"));    Get route from API Getroute (origin, destination);    } private Directionsroute currentroute = null; private void Getroute (waypoint origin, waypoint destination) {mapboxdirections directions = new mapboxdirections.b Uilder (). Setaccesstoken (Mapbox_access_TOKEN). Setorigin (Origin). Setdestination (destination). Setprofile (Directions        criteria.profile_walking). build (); Directions.enqueue (New callback<directionsresponse> () {@Override public void Onresponse (RESPO                nse<directionsresponse> response, Retrofit Retrofit) {//Print some info about the route                Currentroute = Response.body (). Getroutes (). get (0);                Showtoastmessage (String.Format ("You are%d meters \nfrom your destination", currentroute.getdistance ()));            Draw the route on the map Drawroute (Currentroute); } @Override public void OnFailure (Throwable t) {showtoastmessage ("Error:" + t.getme            Ssage ());    }        });    private void Showtoastmessage (String message) {Toast.maketext (context, message, Toast.length_short). Show (); } private void DrawRoute (Directionsroute route) {//Convert list<waypoint> into latlng[] list<waypoint> waypoints        = Route.getgeometry (). getwaypoints ();        latlng[] point = new latlng[waypoints.size ()]; for (int i = 0; i < waypoints.size (); i++) {Point[i] = new LATLNG (Waypoints.get (i). Getl        Atitude (), Waypoints.get (i). Getlongitude ());                }//Draw Points on Mapview mapboxmap.addpolyline (New Polylineoptions (). Add (Point)    . Color (Color.parsecolor ("#38afea")). Width (5)); /** * Get map data, parameter 1 for obtaining the current center point data;        Data 2 indicates the acquisition of a rectangular area point data * * @param datastyle * @return * * * public String Getpoidatajson (int datastyle) {        String data = null;              String Poiurl = Constants.poi_url;    Request Address String Currentpoint = Getmylocationlatlon ();  Current coordinate String areacoordinates = getareacoordinates (); Rectangular area coordinate String Layerstyle = "Try|cate|shop|hotel|msg";                    Layer condition (write dead) String smartrecommend = "1";               Smart Switch--open String currenttime = Getmytime () by default;               Current time String Zoneoffset = "28800000";                      Time zone cheap value (tentative) int currenrownumber = 100;                             Query page max value int pageSize = 100;        Maximum number of rows per page String user_id = Getmyuseid ();                    if (Datastyle = = 1) {data = "{currentpoint:" +currentpoint + ", Layerstyle:" + Layerstyle +                    ", Smartrecommend:" + Smartrecommend + ", CurrentTime:" + currenttime + ", Zoneoffset:" + Zoneoffset + ", Currenrownumber:" + Currenrownumber + ", Pagesiz        E: "+ PageSize +", user_id: "+ user_id +"} ";  } else if (Datastyle = = 2) {data = "{areacoordinates:" + areacoordinates + ", Layerstyle:" + LayerstYle + ", Smartrecommend:" + Smartrecommend + ", CurrentTime:" + currenttime + ", Zoneoffset:" + Zoneoffset + ", Currenrownumber:" + Currenrownumber + ", p        Agesize: "+ pageSize +", user_id: "+ user_id +"} ";        } logutils.e ("Tag", "Request Map POI data Post_json is: \ n" + data);    return data; }/** * Get user_id * * @return */private String Getmyuseid () {String user_id = Sputils.getin        Itialize (context). GetValue ("user_id", "" ");    return user_id; /** * Gets the coordinates of the current position--longitude, dimension * * @return */public String Getmylocationlatlon () {string currentp        oint = Mapboxmap.getmylocation (). Getlongitude () + "," + mapboxmap.getmylocation (). Getlatitude ();    return currentpoint; /** * Gets the area coordinates that are enclosed by the four-corner coordinates of the visible area-latitude, Longitude mode * * @return */public String getareacoordinates () {Visib Leregion BoUnds = Mapboxmap.getprojection (). Getvisibleregion ();        String TopLeft = bounds.farLeft.getLongitude () + "," + bounds.farLeft.getLatitude ();        String topright = bounds.farRight.getLongitude () + "," + bounds.farRight.getLatitude ();        String bottomleft = bounds.nearLeft.getLongitude () + "," + bounds.nearLeft.getLatitude ();        String bottomright = bounds.nearRight.getLongitude () + "," + bounds.nearRight.getLatitude ();        String areacoordinates = TopLeft + "," + Bottomleft + "," + BottomRight + "," + TopRight + "," + topleft;    return areacoordinates;    }/** * Gets the device number * * @return */public String device_id () {return variables.device_id;    }/** * Get token token * * @return */public String token () {return variables.device_id; }/** *//Gets the current time, format: 15:30:30 * * @return */private String Getmytime () {SimpleDateFormat fo        Rmatter = new SimpleDateFormat ("HH:mm:ss"); Date Curdate = new Date (System.currenttimemillis ());//Gets the current time String strtime = Formatter.format (curdate);    return strtime; }}


Android maps Application New Vision--mapbox Common function Encapsulation Tool class

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.