服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Android - Android编程获取地理位置的经度和纬度实例

Android编程获取地理位置的经度和纬度实例

2021-05-09 20:09残缺的孤独 Android

这篇文章主要介绍了Android编程获取地理位置的经度和纬度实现方法,结合实例形式详细分析了Android操作系统服务调用GPS实现定位的相关技巧,需要的朋友可以参考下

本文实例讲述了android编程获取地理位置的经度和纬度。分享给大家供大家参考,具体如下:

在android应用程序中,可以使用locationmanager来获取移动设备所在的地理位置信息。看如下实例:新建android应用程序testlocation。

1、activity_main.xml布局文件

?
1
2
3
4
5
6
7
8
9
10
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <textview
    android:id="@+id/positionview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />
</linearlayout>

用于显示获取到的位置信息。

2、mainactivity.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.example.testlocation;
import java.util.list;
import android.app.activity;
import android.content.context;
import android.location.location;
import android.location.locationlistener;
import android.location.locationmanager;
import android.os.bundle;
import android.view.menu;
import android.widget.textview;
import android.widget.toast;
public class mainactivity extends activity {
  private textview postionview;
  private locationmanager locationmanager;
  private string locationprovider;
  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
    //获取显示地理位置信息的textview
    postionview = (textview) findviewbyid(r.id.positionview);
    //获取地理位置管理器
    locationmanager = (locationmanager) getsystemservice(context.location_service);
    //获取所有可用的位置提供器
    list<string> providers = locationmanager.getproviders(true);
    if(providers.contains(locationmanager.gps_provider)){
      //如果是gps
      locationprovider = locationmanager.gps_provider;
    }else if(providers.contains(locationmanager.network_provider)){
      //如果是network
      locationprovider = locationmanager.network_provider;
    }else{
      toast.maketext(this, "没有可用的位置提供器", toast.length_short).show();
      return ;
    }
    //获取location
    location location = locationmanager.getlastknownlocation(locationprovider);
    if(location!=null){
      //不为空,显示地理位置经纬度
      showlocation(location);
    }
    //监视地理位置变化
    locationmanager.requestlocationupdates(locationprovider, 3000, 1, locationlistener);
  }
  /**
   * 显示地理位置经度和纬度信息
   * @param location
   */
  private void showlocation(location location){
    string locationstr = "维度:" + location.getlatitude() +"\n"
        + "经度:" + location.getlongitude();
    postionview.settext(locationstr);
  }
  /**
   * locationlistern监听器
   * 参数:地理位置提供器、监听位置变化的时间间隔、位置变化的距离间隔、locationlistener监听器
   */
  locationlistener locationlistener = new locationlistener() {
    @override
    public void onstatuschanged(string provider, int status, bundle arg2) {
    }
    @override
    public void onproviderenabled(string provider) {
    }
    @override
    public void onproviderdisabled(string provider) {
    }
    @override
    public void onlocationchanged(location location) {
      //如果位置发生变化,重新显示
      showlocation(location);
    }
  };
  @override
  protected void ondestroy() {
    super.ondestroy();
    if(locationmanager!=null){
      //移除监听器
      locationmanager.removeupdates(locationlistener);
    }
  }
  @override
  public boolean oncreateoptionsmenu(menu menu) {
    // inflate the menu; this adds items to the action bar if it is present.
    getmenuinflater().inflate(r.menu.main, menu);
    return true;
  }
}

从上面可以看出,获取地理位置信息主要分如下步骤:

(1)获取locationmanager实例,通过getsystemservice方法,传入context.location_service参数。
(2)获取可用的位置提供器,有gps_provider、network_provider、passive_provider三种,前两种比较常用。
(3)将(2)获取到的位置提供器传入locationmanager的方法getlastknownlocation,即可获取location信息。
如果移动设备地理位置不断发生变化,则实时更新需要进行如下步骤:
(4)调用locationmanager的requestlocationupdates方法,第一个参数是位置提供器,第二个参数是监听位置变化的时间间隔(毫秒),第三个参数是监听位置变化的距离间隔(米),第四个参数是locationlistener监听器
(5)当位置发生变化后,就会调用监听器的onlocationchanged方法。
(6)为了省电,节约资源,当程序关闭后,调用locationmanager的removeupdates方法移除监听器。

3、获取权限

修改androidmanifest.xml,添加如下代码:

?
1
2
3
<uses-permission android:name="android.permission.access_fine_location"/>
<uses-permission android:name="android.permission.access_coarse_location" />
<uses-permission android:name="android.permission.access_coarse_location"/>

4、效果

使用模拟器进行测试:点击send

Android编程获取地理位置的经度和纬度实例

Android编程获取地理位置的经度和纬度实例

可以使用geocoding api查找具体对应的位置。如下:

(1)修改mainactivity.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package com.example.testlocation;
import java.util.list;
import org.apache.http.httpentity;
import org.apache.http.httpresponse;
import org.apache.http.client.httpclient;
import org.apache.http.client.methods.httpget;
import org.apache.http.impl.client.defaulthttpclient;
import org.apache.http.util.entityutils;
import org.json.jsonarray;
import org.json.jsonobject;
import android.app.activity;
import android.content.context;
import android.location.location;
import android.location.locationlistener;
import android.location.locationmanager;
import android.os.bundle;
import android.os.handler;
import android.os.message;
import android.view.menu;
import android.widget.textview;
import android.widget.toast;
public class mainactivity extends activity {
  private textview postionview;
  private locationmanager locationmanager;
  private string locationprovider;
  public static final int show_location = 0;
  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
    //获取显示地理位置信息的textview
    postionview = (textview) findviewbyid(r.id.positionview);
    //获取地理位置管理器
    locationmanager = (locationmanager) getsystemservice(context.location_service);
    //获取所有可用的位置提供器
    list<string> providers = locationmanager.getproviders(true);
    if(providers.contains(locationmanager.gps_provider)){
      //如果是gps
      locationprovider = locationmanager.gps_provider;
    }else if(providers.contains(locationmanager.network_provider)){
      //如果是network
      locationprovider = locationmanager.network_provider;
    }else{
      toast.maketext(this, "没有可用的位置提供器", toast.length_short).show();
      return ;
    }
    //获取location
    location location = locationmanager.getlastknownlocation(locationprovider);
    if(location!=null){
      //不为空,显示地理位置经纬度
      showlocation(location);
    }else{
      toast.maketext(this, "location为空", toast.length_short).show();
    }
    //监视地理位置变化
    locationmanager.requestlocationupdates(locationprovider, 3000, 1, locationlistener);
  }
  private handler handler = new handler(){
    public void handlemessage(message msg){
      switch(msg.what){
      case show_location:
        string position = (string) msg.obj;
        postionview.settext(position);
        break;
      default:
        break;
      }
    }
  };
  /**
   * 显示地理位置经度和纬度信息
   * @param location
   */
  private void showlocation(final location location){
    /*string locationstr = "维度:" + location.getlatitude() +"\n"
        + "经度:" + location.getlongitude();
    postionview.settext(locationstr);*/
    new thread(new runnable() {
      @override
      public void run() {
        try{
          //组装反向地理编码的接口位置
          stringbuilder url = new stringbuilder();
          url.append("http://maps.googleapis.com/maps/api/geocode/json?latlng=");
          url.append(location.getlatitude()).append(",");
          url.append(location.getlongitude());
          url.append("&sensor=false");
          httpclient client = new defaulthttpclient();
          httpget httpget = new httpget(url.tostring());
          httpget.addheader("accept-language","zh-cn");
          httpresponse response = client.execute(httpget);
          if(response.getstatusline().getstatuscode() == 200){
            httpentity entity = response.getentity();
            string res = entityutils.tostring(entity);
            //解析
            jsonobject jsonobject = new jsonobject(res);
            //获取results节点下的位置信息
            jsonarray resultarray = jsonobject.getjsonarray("results");
            if(resultarray.length() > 0){
              jsonobject obj = resultarray.getjsonobject(0);
              //取出格式化后的位置数据
              string address = obj.getstring("formatted_address");
              message msg = new message();
              msg.what = show_location;
              msg.obj = address;
              handler.sendmessage(msg);
            }
          }
        }catch(exception e){
          e.printstacktrace();
        }
      }
    }).start();
  }
  /**
   * locationlistern监听器
   * 参数:地理位置提供器、监听位置变化的时间间隔、位置变化的距离间隔、locationlistener监听器
   */
  locationlistener locationlistener = new locationlistener() {
    @override
    public void onstatuschanged(string provider, int status, bundle arg2) {
    }
    @override
    public void onproviderenabled(string provider) {
    }
    @override
    public void onproviderdisabled(string provider) {
    }
    @override
    public void onlocationchanged(location location) {
      //如果位置发生变化,重新显示
      showlocation(location);
    }
  };
  @override
  protected void ondestroy() {
    super.ondestroy();
    if(locationmanager!=null){
      //移除监听器
      locationmanager.removeupdates(locationlistener);
    }
  }
  @override
  public boolean oncreateoptionsmenu(menu menu) {
    // inflate the menu; this adds items to the action bar if it is present.
    getmenuinflater().inflate(r.menu.main, menu);
    return true;
  }
}

(2)修改androidmanifest.xml

?
1
2
3
4
<uses-permission android:name="android.permission.access_fine_location"/>
<uses-permission android:name="android.permission.access_coarse_location" />
<uses-permission android:name="android.permission.access_coarse_location"/>
<uses-permission android:name="android.permission.internet"/>

希望本文所述对大家android程序设计有所帮助。

延伸 · 阅读

精彩推荐