Today, in the android project, you need to implement a GPS or network function to obtain the longitude and latitude of the current mobile terminal device. To implement this function, you must use the locationmanager class in the android framework. Next I will directly paste the main code to illustrate how to obtain the longitude and latitude of a real-time location through GPS or network.
Private double latitude = 0.0; <br/> private double longpolling = 0.0; </P> <p> locationmanager = (locationmanager) getsystemservice (context. location_service); <br/> If (locationmanager. isproviderenabled (locationmanager. gps_provider) {<br/> location = locationmanager. getlastknownlocation (locationmanager. gps_provider); <br/> If (location! = NULL) {<br/> latitude = location. getlatitude (); <br/> longdistance = location. getlonglistener (); <br/>}< br/>} else {<br/> locationlistener = new locationlistener () {</P> <p> // This function is triggered when the provider status is directly switched to the available, temporarily unavailable, or unavailable status. <br/> @ override <br/> public void onstatuschanged (string provider, int status, bundle extras) {</P> <p >}</P> <p> // This function is triggered when the provider is enabled, for example, if GPS is enabled <br/> @ override <br/> Public void ONP Roviderenabled (string provider) {</P> <p >}</P> <p> // This function is triggered when the provider is disable, for example, if GPS is disabled <br/> @ override <br/> Public void onproviderdisabled (string provider) {</P> <p >}</P> <p> // This function is triggered when the coordinates change. If the provider transmits the same coordinates, it will not be triggered <br/> @ override <br/> Public void onlocationchanged (location) {<br/> If (location! = NULL) {<br/> log. E ("map", "location changed: Lat:" <br/> + location. getlatitude () + "LNG:" <br/> + location. getlongpolling (); <br/>}< br/>}; <br/> locationmanager. requestlocationupdates (locationmanager. network_provider, 1000, 0, locationlistener); <br/> location = locationmanager. getlastknownlocation (locationmanager. network_provider); <br/> If (location! = NULL) {<br/> latitude = location. getlatitude (); // longitude <br/> longdistance = location. getlongpolling (); // latitude <br/>}< br/>}
Do not forget to add the following permissions to the androidmanifest. xml file:
<! -- Internet access permission -->
<Uses-Permission Android: Name = "android. Permission. Internet"/>
<! -- GPS Positioning permission -->
<Uses-Permission Android: Name = "android. Permission. access_coarse_location"/>
<Uses-Permission Android: Name = "android. Permission. access_fine_location"/>
Note: I have tested the above functions on a real machine to obtain the longitude and latitude of the real-time mobile terminal.