您的位置:首页 > 移动开发 > Android开发

MONO For Android学习笔记之使用Location服务获取位置

2015-04-23 15:23 246 查看
使自己的应用获取位置时记得要给应用ACCESS_FINE_LOCATION权限打钩。如下图:

下面是全部应用代码:</pre><pre name="code" class="csharp">using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Net;
using System.Text;
using System.Xml;
using Android.Locations;

namespace CS_HQWZ
{
[Activity(Label = "CS_HQWZ", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
TextView txtxx;
double dJD;
double dWD;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);

SetContentView(Resource.Layout.Main);

txtxx = FindViewById<TextView>(Resource.Id.txtxx);
getLocation();
LocationMethod();

}

public Location getLocation()
{ // 获取Location通过LocationManger获取!
LocationManager locManger = (LocationManager)GetSystemService(Context.LocationService);
Location loc = locManger.GetLastKnownLocation(LocationManager.GpsProvider);
if (loc == null)
{
loc = locManger.GetLastKnownLocation(LocationManager.NetworkProvider);
}
return loc;
}

public void LocationMethod()
{ // Location常用方法简介
Location loc = getLocation();

try
{
dJD = loc.Latitude;
dWD = loc.Longitude;
GetWZ();
}
catch (Exception)
{
txtxx.Text = "未获取到当前位置信息,请打开GPS重试。";
}

}

/// <summary>
/// 根据坐标返回位置
/// </summary>
public void GetWZ()
{
WebClient client = new WebClient();//webclient客户端对象
string url = "http://api.map.baidu.com/geocoder/v2/?ak=输入你的百度AK=" + dJD + "," + dWD + "&output=xml&pois=1";//请求地址
client.Encoding = Encoding.UTF8;//编码格式
string responseTest = client.DownloadString(url);//下载xml响应数据

XmlDocument doc = new XmlDocument();//创建XML文档对象

if (!string.IsNullOrEmpty(responseTest))
{
doc.LoadXml(responseTest);//加载xml字符串

//获取状态信息
string xpath = @"GeocoderSearchResponse/status";
XmlNode node = doc.SelectSingleNode(xpath);
string status = node.InnerText.ToString();

if (status == "0")
{
//获取地址信息
xpath = @"GeocoderSearchResponse/result/formatted_address";
node = doc.SelectSingleNode(xpath);
string address = node.InnerText.ToString();

txtxx.Text = "地址是:" + address;
//输出地址信息
}
}

}
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐