广告
返回顶部
首页 > 资讯 > 移动开发 >Android编程获取地理位置的经度和纬度实例
  • 289
分享到

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

获取地理位置地理Android 2022-06-06 09:06:02 289人浏览 薄情痞子
摘要

本文实例讲述了Android编程获取地理位置的经度和纬度。分享给大家供大家参考,具体如下: 在Android应用程序中,可以使用LocationManager来获取移动设备所在

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

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

1、activity_main.xml布局文件


<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


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);
  }
  
  private void showLocation(Location location){
    String locationStr = "维度:" + location.getLatitude() +"\n"
        + "经度:" + location.getLongitude();
    postionView.setText(locationStr);
  }
  
  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,添加如下代码:


<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

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

(1)修改MainActivity.java


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;
      }
    }
  };
  
  private void showLocation(final Location location){
    
    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();
  }
  
  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


<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程序设计有所帮助。

您可能感兴趣的文章:Android 获取系统语言的实例(兼容7.0)详解Android更改APP语言模式的实现过程android 支持的语言列表(汇总)Android 各国语言缩写及简称详细介绍Android实现系统语言切换功能Android app应用多语言切换功能实现Android实现app应用多语言切换功能Android自定义WheelView地区选择三级联动轻松实现Android仿淘宝地区选择功能用Android Location获取当前地理位置的方法Android使用GPS获取用户地理位置并监听位置变化的方法Android编程实现获取当前系统语言及地区并更改语言的方法


--结束END--

本文标题: Android编程获取地理位置的经度和纬度实例

本文链接: https://www.lsjlt.com/news/25908.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作