GoogleMap of Android (2)

Source: Internet
Author: User

As mentioned above, there are several ways to obtain the longitude and latitude of the mobile phone's location.? Location Manager and location are provided through GPS, network, and status API. Here, locationmanager is used to obtain the location service and location is used to obtain the location. DetailsCodeAs follows:

View code

 
 PrivateGeopoint getgeopoint (){
Locationmanager = (locationmanager) getsystemservice (context. location_service );
Location = locationmanager. getlastknownlocation (locationmanager. gps_provider );
Return NewGeopoint ((Int) Location. getlatitude (),(Int) Location. getlongdistance ());
}

Here we can know a latitude and longitude object geopoint, which accepts two integer latitude and longitude values. Here we use GPS to obtain the current longitude and latitude. What if we use network? So long for locationmanager. network_provider

Of course, we may have to consider more cases. For example, if the gps mode is disabled, how can we start it? It's easy. We only need to determine whether GPS is enabled. If not, we need to jump to settings to enable GPS. The Code is as follows:

View code

 
BooleanFlag = locationmanager. isproviderenabled (locationmanager. gps_provider );
If(! Flag ){
Intent intent =NewIntent (settings. action_security_settings );
}

The preceding figure shows the longitude and latitude of the current mobile phone location.

Of course, when we walk, the location is constantly changing. How can we detect and display the location changes?

Here we need to use the location listener locationlistener. Of course, we will query the best data, so we need to set criteria

The Code is as follows:

View code

 //  Get the best service  
Private Criteria getcriteria (){
Criteria = New Criteria ();
Criteria. setaccuracy (criteria. accuracy_fine ); // High Precision
Criteria. setaltituderequired ( False ); // Altitude
Criteria. setbearingrequired ( False ); // Geographic axis
Criteria. setcostallowed ( False ); // Payment
Criteria. setpowerrequirement (criteria. power_low ); // Low Power
Return Criteria;
}

Instantiate locationlistener and process it in different callback functions. Here we only process the onlocationchanged callback function. The specific code is as follows:

View code

 // Location listener, which changes the listening position  
Locationlistener = New Locationlistener (){
// Triggered when location changes
@ Override
Public Void Onlocationchanged (location ){
// Obtain latitude and longitude objects by location
Getgeopoint (location );
}
// When GPS or network is available
@ Override
Public Void Onproviderdisabled (string provider ){


}
// Triggered when GPS or network is unavailable
@ Override
Public Void Onproviderenabled (string provider ){


}
// Triggered when the GPS or network status changes
@ Override
Public Void Onstatuschanged (string provider, Int Status, bundle extras ){
Switch (Status ){
Case Locationprovider. out_of_service:
// Not in Service
Break ;
Case Locationprovider. temporarily_unavailable:
// Unavailable currently
Break ;
Case Locationprovider. Available:
// Available
Break ;

}

}
};

After the listener processing class is defined, we can register the listener in locationmanager:

View code

 Private   Void Registelistener (){
Locationmanager = (locationmanager) getsystemservice (context. location_service );
If (! Locationmanager. isproviderenabled (locationmanager. gps_provider )){
// If GPS is not available, go to settings to set
Intent intent = New Intent (settings. action_security_settings );
Startactivity (intent );
}
// Query the most specific service information
String provider = locationmanager. getbestprovider (getcriteria (), True );
// Set the location listener. The interval is changed once every 5 seconds.
Locationmanager. requestlocationupdates (provider, 5000, 0, locationlistener );
}

Here, locationmanager. requestlocationupdates (provider, 5000, 0, locationlistener ), the first class is the listener class.

Of course, we can cancel location listening: locationmanager. removeupdates (locationlistener );

Since we can dynamically obtain the mobile phone longitude and latitude, how can we resolve the longitude and latitude to our actual address?
We can use the getfromlocation method of the geocoder class to parse the location information, then return a list of address information <address>, and then obtain the address information of the country, state, county, street, and so on based on the most suitable address, the Code is as follows:

View code

 //  Obtain the address based on the longitude and latitude (country, state, county, street, etc)  
Private Void Showaddressfromgeopoint (geopoint gpoint) Throws Ioexception {
Stringbuilder sb = New Stringbuilder ();
Geocoder geocode = New Geocoder (This , Locale. getdefault ());
List <address> addresses = geocode. getfromlocation (gpoint. getlatitudee6 ()/1e6, gpoint. getlongitudee6 ()/1e6, 1 );
If (Addresses. Size ()> 0 ){
Address = addresses. Get (0 );
For ( Int I = 0; I <address. getmaxaddresslineindex (); I ++ ){
SB. append (address. getaddressline (I) + "\ n ");
}
SB. append (address. getlocality () + "\ n ");
SB. append (address. getpostalcode () + "\ n ");
SB. append (address. getcountryname () + "\ n ");

Toast. maketext ( This , SB. tostring (), Toast. length_long). Show ();
}
}

The preceding section resolves the longitude, latitude, and position information into an address. In turn, can we obtain the longitude and latitude positions based on the address name and then identify them on the map? Of course you can. Now you can obtain the longitude and latitude based on the actual address:

As in the preceding method, call the getfromlocationname method of geocoder to obtain the address list, obtain the optimal address, and obtain the longitude and latitude. The Code is as follows:

View code

  //  Obtain latitude and longitude information geopoint Based on the address  
Private Geopoint getgeopointfromaddressname (string locationname)Throws Ioexception {
Geocoder geocode = New Geocoder ( This , Locale. getdefault ());
List <address> addresses = geocode. getfromlocationname (locationname, 1 );
If (Addresses! = Null ){
Double Lati = addresses. Get (0). getlatitude ();
Double Longi = addresses. Get (0). getlongsums ();
Return New Geopoint (( Int ) (Lati * 1e6 ),( Int ) (Longi * 1e6 ));
}
Return Null ;
}

If I want to know if I have approached a certain area and the mobile phone sends a notification, what should I do?

The distancebetween method of location is used to measure the distance between the two points and the geopoint of the latitude and longitude object is fixed. The Code is as follows:

View code

 //Calculate the 2-point distance, longitude and latitude
Private FloatGetdistance (geopoint startpoint, geopoint endpoint ){
Float[] Results =New Float[3];
Location. distancebetween (startpoint. getlatitudee6 ()/1e6, startpoint. getlongitudee6 ()/1e6,
Endpoint. getlatitudee6 ()/1e6, endpoint. getlongitudee6 ()/1e6,
Results );
ReturnResults [0];
}

The above code detects the distance between two points. Then we can determine whether the distance between two points is within a certain distance. The Code is as follows:

View code

//Determine the number of meters in the range
Private BooleanIsneararound (geopoint startpoint, geopoint endpoint,FloatMeter ){
FloatDistance = getdistance (startpoint, endpoint );
Return(Meter-distance> 0 )?True:False;
}

The above is the method of approaching a certain range, but you may think, what if our position is changed? Therefore, you must update the geopoint when the location changes. The location change listener locationlistener has an onlocationchanged method to call back the location of each change. Of course, after reading the above instructions, you will naturally know how to call it.

There are several other issues that may often occur during development.

How can we obtain the longitude and latitude corresponding to a point on the mobile phone screen? (Mobile Phone screen points are converted to longitude and latitude),Or how does one correspond to a point on the mobile phone screen at a longitude or latitude?

We can use the frompixels method of the projection class and the topixels method to convert them to a screen point and the latitude and longitude of the screen point. Of course, obtaining projection requires the getprojection method of our map object. The Code is as follows:

View code

  //   obtain longitude and latitude from a point on the screen   
private geopoint formscreenpoint (point screen) {
projection = mapview. getprojection ();
geopoint gpoint = projection. frompixels (screen. x, screen. y);
return gpoint;
}< br> /// locate a point on the mobile phone screen based on the longitude and latitude
private point fromgeopoint (geopoint gpoint) {
point out = New point ();
projection = mapview. getprojection ();
projection. topixels (gpoint, out);
return out;
}

With the previous basic knowledge, we can further develop. As mentioned above, we can draw a layer on the screen of the mobile phone to mark an image or some information, then we click this tag and it will prompt some information.
Here is how to mark the map.
An overlay class is used here, which can be used as a tag on the map. Therefore, we first base this tag, then draw our own graph (image), and then rewrite its ontouchevent method, so that information is prompted when you click this layer. Of course, we can pass the geopoint object of latitude and longitude to display it in the MAP:

View code

 //  Custom layer tag  
Private Class Myoverlay Extends Overlay {
Geopoint in = Null ;
Public Myoverlay (geopoint in ){
This . In = in;
}
// Add a map pin (an image) to the custom Drawing Layer Method)
@ Override
Public Boolean Draw (canvas, mapview,
Boolean Shadow, Long When ){
// Adjust the longitude and latitude of the screen
Point out =New Point ();
Projection proj = mapview. getprojection ();
Proj. topixels (In, out );

// Obtain the image and call canvas to draw the image. The first parameter is the Y axis coordinate.
Bitmap bitmap = bitmapfactory. decoderesource (getresources (), R. drawable. ic_launcher );
Canvas. drawbitmap (bitmap, out. X, out. y-50, Null );
Return True ;
}

@ Override
Public Boolean Ontouchevent (motionevent E, mapview ){
If (E. getaction () = motionevent. action_up ){
// Obtain the longitude and latitude Based on the screen.
Geopoint gpoint = mapview. getprojection (). frompixels (( Int ) E. getx (),( Int ) E. Gety ());
// Then display the longitude and latitude
String MSG = "the longitude where you click is:" + gpoint. getlatitudee6 ()/1e6 + ", latitude:" + gpoint. getlongitudee6 ()/1e6;
Toast. maketext (getapplication (), MSG, Toast. length_long). Show ();

// Of course, you can use the passed objects, such as geopoint to obtain information about other custom objects, such as places, companies, scenic spots, etc.

}
Return True ;
}
}

We can see that we have drawn a graph and rewritten the touch method to prompt information during the touch. Next, we must "pin" it to the map for display. Of course, by default, mapview automatically loads layers. You only need to call
List <overlay> overlays = mapview. getoverlays (); The method obtains the layer list and adds the custom layer. The Code is as follows:

View code

 
 //Mark on the screen (graph)
Private VoidPutoverlay (geopoint in ){
///Define tag
Myoverlay =NewMyoverlay (in );
List <overlay> overlays = mapview. getoverlays ();
Overlays. Clear ();
Overlays. Add (myoverlay );
Mapview. invalidate ();
}

Here is a problem resolved, we say canvas. drawbitmap (bitmap, out. X, out. y-50, null); in the 3rd parameter is to subtract 50? You can see from this figure that the pointer of the graph dingtalk corresponds to a certain point on the screen only after the height is subtracted.

Complete. If you fully understand the above series of things, then lbs has a foundation.

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.