对于使用经纬度得到位置Geocorder感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解使用经纬度定位,并且为您提供关于Android:原生的手机获取经纬度得到当前位置、angular.js
对于使用经纬度得到位置Geocorder感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解使用经纬度定位,并且为您提供关于Android:原生的手机获取经纬度得到当前位置、angular.js codovar之geolocation获取经纬度、C#如何提取经纬度文件中的经纬度数据、C#调用百度地图API根据地名获取经纬度geocoding的宝贵知识。
本文目录一览:- 使用经纬度得到位置Geocorder(使用经纬度定位)
- Android:原生的手机获取经纬度得到当前位置
- angular.js codovar之geolocation获取经纬度
- C#如何提取经纬度文件中的经纬度数据
- C#调用百度地图API根据地名获取经纬度geocoding
使用经纬度得到位置Geocorder(使用经纬度定位)
先得到经纬度再用geocorder 显示位置,需要手机打开位置权限,使用GPS的话把注释去掉,GPS在室内很容易收不到信号,得到位置为空
public class MainActivity extends AppCompatActivity {
private LocationManager lm;
double latitude;
double longitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ? true : false) {
// Toast.makeText(MainActivity.this, "请打开GPS~", Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
// startActivityForResult(intent, 0);
// }
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//位置权限打开检查
return;
}
Location location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
System.out.println("经度"+longitude);
}
//设置间隔两秒获得一次GPS定位信息
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 8, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// 当GPS定位信息发生改变时,更新定位
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@SuppressLint("MissingPermission")
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
});
Geocoder gc = new Geocoder(this, Locale.getDefault());
List<Address> address = null;
try {
address = gc.getFromLocation(latitude, longitude, 1);
} catch(IOException e){
e.printStackTrace();
}
Address address2 = address.get(0);//得到Address实例
//Log.i(TAG, "address =" + address);
String countryName = address2.getCountryName();//得到国家名称,比方:中国
System.out.println("countryName = "+countryName);
String locality = address2.getLocality();//得到城市名称,比方:北京市
System.out.println("locality = "+locality);
for(int i = 0; address2.getAddressLine(i)!=null;i++)
{
String addressLine = address2.getAddressLine(i);//得到周边信息。包含街道等。i=0,得到街道名称
System.out.println("addressLine = " + addressLine);
}
}
}
xmlns:tools="http://schemas.android.com/tools"
package="com.january.spring">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
如果8.0以下geocoder可能无法得到,要把它放在线程执行里才行
Android:原生的手机获取经纬度得到当前位置
这是一套完整的代码,模拟器与真机调试可用
1.首先得注册权限
android:name="android.permission.ACCESS_COARSE_LOCATION"
android:name="android.permission.ACCESS_FINE_LOCATION"
1.1其次最重要的是,申请权限,一直真机调试不成功,折磨死我啦,放在protected void onCreate方法就可以
if(ContextCompat.checkSelfPermission(EventsReportedActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){//未开启定位权限
//开启定位权限,200是标识码
ActivityCompat.requestPermissions(EventsReportedActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},200);
}else{
initLocation();//初始化定位信息
Toast.makeText(EventsReportedActivity.this,"已开启定位权限", Toast.LENGTH_LONG).show();
}
1.2这边再回调一下
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 200://刚才的识别码
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){//用户同意权限,执行我们的操作
initLocation();//开始定位
}else{//用户拒绝之后,当然我们也可以弹出一个窗口,直接跳转到系统设置页面
Toast.makeText(EventsReportedActivity.this,"未开启定位权限,请手动到设置去开启权限",Toast.LENGTH_LONG).show();
}
break;
default:break;
}
}
写到这里差不多就结束啦,
2.获取经纬度
2.1工具类
package com.skyinfor.szls.Util;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import androidx.core.app.ActivityCompat;
import java.util.List;
import static android.content.ContentValues.TAG;
public class LocationUtils {
private volatile static LocationUtils uniqueInstance;
private LocationManager locationManager;
private String locationProvider;
private Location location;
private Context mContext;
private LocationUtils(Context context) {
mContext = context;
getLocation();
}
//采用Double CheckLock(DCL)实现单例
public static LocationUtils getInstance(Context context) {
if (uniqueInstance == null) {
synchronized (LocationUtils.class) {
if (uniqueInstance == null) {
uniqueInstance = new LocationUtils(context);
}
}
}
return uniqueInstance;
}
private void getLocation() {
//1.获取位置管理器
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
//2.获取位置提供器,GPS或是NetWork
List<String> providers = locationManager.getProviders(true);
if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
//如果是网络定位
Log.d(TAG, "如果是网络定位");
locationProvider = LocationManager.NETWORK_PROVIDER;
} else if (providers.contains(LocationManager.GPS_PROVIDER)) {
//如果是GPS定位
Log.d(TAG, "如果是GPS定位");
locationProvider = LocationManager.GPS_PROVIDER;
} else {
Log.d(TAG, "没有可用的位置提供器");
return;
}
// 需要检查权限,否则编译报错,想抽取成方法都不行,还是会报错。只能这样重复 code 了。
if (Build.VERSION.SDK_INT >= 23 &&
ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
//3.获取上次的位置,一般第一次运行,此值为null
Location location = locationManager.getLastKNownLocation(locationProvider);
if (location != null) {
setLocation(location);
}
// 监视地理位置变化,第二个和第三个参数分别为更新的最短时间minTime和最短距离mindistace
locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
}
private void setLocation(Location location) {
this.location = location;
String address = "纬度:" + location.getLatitude() + "经度:" + location.getLongitude();
Log.d(TAG, address);
}
//获取经纬度
public Location showLocation() {
return location;
}
// 移除定位监听
public void removeLocationUpdatesListener() {
// 需要检查权限,否则编译不过
if (Build.VERSION.SDK_INT >= 23 &&
ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (locationManager != null) {
uniqueInstance = null;
locationManager.removeUpdates(locationListener);
}
}
/**
* 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) {
location.getAccuracy();//精确度
setLocation(location);
}
};
}
2.2调用
private void initLocation(){
Location location = LocationUtils.getInstance( EventsReportedActivity.this ).showLocation();
if (location != null) {
String address = "纬度:" + location.getLatitude() + "经度:" + location.getLongitude();
Log.d( "FLY.LocationUtils", address );
//text_location.setText( address );
text_location.setText( getAddress(location.getLongitude(),location.getLatitude()));
}
}
3.转为具体地址
3.1方法
public String getAddress(double lnt, double lat) {
Geocoder geocoder = new Geocoder(EventsReportedActivity.this);
boolean falg = geocoder.isPresent();
Log.e("the falg is " + falg,"the falg is ");
StringBuilder stringBuilder = new StringBuilder();
try {
//根据经纬度获取地理位置信息---这里会获取最近的几组地址信息,具体几组由最后一个参数决定
List<Address> addresses = geocoder.getFromLocation(lat, lnt, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
//每一组地址里面还会有许多地址。这里我取的前2个地址。xxx街道-xxx位置
if (i == 0) {
stringBuilder.append(address.getAddressLine(i)).append("-");
}
if (i == 1) {
stringBuilder.append(address.getAddressLine(i));
break;
}
}
//stringBuilder.append(address.getCountryName()).append("");//国家
stringBuilder.append(address.getAdminArea()).append("");//省份
stringBuilder.append(address.getLocality()).append("");//市
stringBuilder.append(address.getFeatureName()).append("");//周边地址
// stringBuilder.append(address.getCountryCode()).append("_");//国家编码
// stringBuilder.append(address.getThoroughfare()).append("_");//道路
Log.d("thistt", "地址信息--->" + stringBuilder);
}
} catch (Exception e) {
Log.d("获取经纬度地址异常","");
e.printstacktrace();
}
return stringBuilder.toString();
}
3.2调用
String Address = getAddress(location.getLongitude(),location.getLatitude());
angular.js codovar之geolocation获取经纬度
1.安装定位插件
cmd切换至项目目录执行
cordova plugin add org.apache.cordova.geolocation
2.例子
$scope.getGeolocation = function() {
function onSuccess(position) {
console.log(
''Latitude纬度: '' + position.coords.latitude + ''\n'' +
''Longitude经度: '' + position.coords.longitude + ''\n'' +
''Altitude海拔: '' + position.coords.altitude + ''\n'' +
''Accuracy精度: '' + position.coords.accuracy + ''\n'' +
''Altitude Accuracy: '' + position.coords.altitudeAccuracy + ''\n'' +
''Heading: '' + position.coords.heading + ''\n'' +
''Speed: '' + position.coords.speed + ''\n'' +
''Timestamp: '' + position.timestamp + ''\n'');
$scope.latitude = position.coords.latitude;//纬度
$scope.longitude = position.coords.longitude;//经度
};
function onError(error) {
console.log(''code: '' + error.code + ''\n'' + ''message: '' + error.message + ''\n'');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
$scope.getGeolocation();
执行$scope.getGeolocation(),当前纬度经度已赋值给$scope.latitud 和 $scope.longitude
C#如何提取经纬度文件中的经纬度数据
前言:
之前我们使用对List将数据封装进KML经纬度文件中,今天我们来学习一下如何将经纬度文件中的经纬度数据读出来,并保存在变量中,这个变量可以是list也可以是数组,只要能储存数据就可以,我们对KML文件中的Point数据下面的coordinates数据读出来即可!!!
一、界面设计
设计了两个选项,可以选择不同的效果进行提取经纬度数据,第一代表可以把数据提取到TXT文本文件中,而第二表示不会生成TXT文件只在文本框中展示你的提取数据,可以看后面的代码逻辑,有一个函数是专门负责数据的提取,是使用XML读取的形式读取指定的标签数据
二、效果展示
目前只展示了不会导出TXT文件的效果,只是对数据展示在文本框中。你们也可以按照自己的需求接着写接着添加自己想要的功能,后面有代码逻辑,代码也有注解,不至于不能懂,有啥问题评论区评论
三、代码逻辑
使用的是XML文件读取的形式,利用XML的节点的方式,对数据的标签遍历得到,对应的标签,再对指定的coordinates标签的数据进行提取并赋值,从而实现提取KML文件中的经纬度的数据效果。
//自定义类的函数 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; namespace FileConversion { public class DataExtract { /// <summary> /// 对指定路径的kml文件,经纬度读取,并返回经纬度集合MapConfig /// </summary> /// <param name="Path">文件路径名</param> /// <returns></returns> public List<String> MapConfigs(string filename) { List<String> mapConfigs = new List<String>();//实例化list集合 string destPath = filename;//赋值文件路径 if (destPath == null)//判断路径是否为空 { MessageBox.Show("路径为空"); return null; } XmlDocument xmldoc = new XmlDocument(); try { xmldoc.Load(destPath);//加载kml文件 XmlElement root = xmldoc.DocumentElement; XmlNodeList xmlmark = root.GetElementsByTagName("coordinates");//获取coordinates节点 int i = 0; foreach (XmlNode xmlmarkNode in xmlmark)//遍历所有coordinates节点 { if (xmlmarkNode.Name == "coordinates") { i++; string mapConfig = "";//实例化 string str = xmlmarkNode.InnerText;//获取节点的值 if (str.Equals("") || str.Contains(",") == false) { MessageBox.Show("第"+i.ToString()+"行数据有误,将返回NULL值","错误"); return null; } string[] strings = str.Split('','');//对节点的值字符串进行分割 mapConfig+= strings[0]+",";//经度值 mapConfig+= strings[1]+",";//纬度值 mapConfig+= strings[2];// mapConfigs.Add(mapConfig);//添加在list中 } } return mapConfigs; } catch { MessageBox.Show("文件加载失败或coordinates节点数据获取失败", "错误"); return null;//注:kml文件如果使用wps或者word打开会再运行本程序会报错,文本打开运行不会报错 } } } } //上面是我们需要调用的类 //这个是我们界面设计调用的类 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FileConversion { public partial class Form4 : Form { public Form4() { InitializeComponent(); } public string KmlPath = ""; private void button6_Click(object sender, EventArgs e) { OpenFileDialog openFile = new OpenFileDialog(); openFile.Filter = "KML文件(*.kml)|*.kml|所有文件|*.*"; if (openFile.ShowDialog() != DialogResult.OK)//打开文件是否点击了取消 return; KmlPath = openFile.FileName; textBox1.Text = KmlPath; } private void button7_Click(object sender, EventArgs e) { DataExtract data = new DataExtract();//自定义的函数,复制kml文件经纬度数据提取 if (KmlPath.Equals("") == true) { MessageBox.Show("选择文件之后才能导出"); } else { if (checkBox1.Checked == true && checkBox2.Checked == false || checkBox1.Checked == true && checkBox2.Checked == true) { List<string> list = data.MapConfigs(KmlPath); string localFilePath = "";//文件路径 SaveFileDialog save = new SaveFileDialog(); save.Filter = "Txt(*.txt)|*.txt"; //设置文件类型 save.RestoreDirectory = true; //保存对话框是否记忆上次打开的目录 if (save.ShowDialog() == DialogResult.OK)//点了保存按钮进入 { localFilePath = save.FileName.ToString(); //获得文件路径 string fileName = localFilePath.Substring(localFilePath.LastIndexOf("\") + 1); //获取文件名,不带路径 //FileStream file = new FileStream(localFilePath, FileMode.Create); foreach (string kml in list) { textBox2.Text += kml + "\r\n"; File.AppendAllText(localFilePath, kml + "\r\n"); } } } else if (checkBox1.Checked == false && checkBox2.Checked == true) { List<string> list = data.MapConfigs(KmlPath); foreach (string kml in list) { textBox2.Text += kml + "\r\n"; } } else { MessageBox.Show("选择你需要的项"); } } } } }
总结:
这篇文章比较简单,里面也已经写好了方法让我们调用就可以了,界面制作比较简单,但是是一个比较实用的一个小工具。
到此这篇关于C#如何提取经纬度文件中经纬度数据的文章就介绍到这了,更多相关C#提取经纬度数据内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
- C#通过经纬度计算2个点之间距离的实现代码
- c# 通过经纬度查询 具体的地址和区域名称
- c# 获取照片的经纬度和时间的示例代码
- C#调用百度地图API根据地名获取经纬度geocoding
C#调用百度地图API根据地名获取经纬度geocoding
前言
公司的一个内部网站维护,需要根据地名填写经纬度,最终同echarts生成地图。
之前数据比较少,直接经纬度查询查的,https://jingweidu.bmcx.com/
现在数据越来越多,手动查询太麻烦,于是想到通过地图api批量查询,最后选择了百度地图API。
步骤 一、到百度地图开放平台注册认证,并创建应用,获取ak
百度地图开放平台:https://lbsyun.baidu.com/apiconsole/key#/home
二、查看api文档
根据地名获取经纬度的接口,可以使用逆地理编码
https://api.map.baidu.com/geocoding/v3/?address=北京市海淀区上地十街10号&output=json&ak=您的ak&callback=showLocation //GET请求
接口功能介绍如下https://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding
查看请求参数
可以看到几个主要的参数address,ak,output
、查看返回结果参数
status为返回结果状态值,成功返回0,其它值都是失败
三、创建GeocodingMap类,根据地名获取经纬度
根据api返回结果参数,创建结果模型
public class GeocodingResult { public int status { get; set; } = -1; public string msg { get; set; } public Result result { get; set; } } public class Result { public Location location { get; set; } public int precise { get; set; } public int confidence { get; set; } public int comprehension { get; set; } public string level { get; set; } } public class Location { public float lng { get; set; } public float lat { get; set; } }
创建几个类,存储ak,请求url,获取经纬度,为了演示方便,这里将几个类写在一起
public class Config { public static string Ak { get; set; } = "xxxxxxxxxxxxxx";//这里根据实际填写,填写刚才申请的应用ak } public class HttpRequestHelper { public static async Task<string> RequestUrl(string url) { string content = string.Empty; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader sr = new StreamReader(response.GetResponseStream())) { content = await sr.ReadToEndAsync(); } } return content; } } public class GeocodingMap { public static async Task<GeocodingResult> GetGeocoding(string address) { //API 文档:https://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding string url = @$"https://api.map.baidu.com/geocoding/v3/?address={address}&output=json&ak={Config.Ak}"; string strJson = await HttpRequestHelper.RequestUrl(url); var requestResult = JsonSerializer.Deserialize<GeocodingResult>(strJson); return requestResult; } }
调用
var geocoding = await GeocodingMap.GetGeocoding(address); if (geocoding.status == 0) { //经纬度 var axisX = geocoding.result.location.lng; var axisY = geocoding.result.location.lat }
参考
百度地图API根据地名获取经纬度 - 慕尼黑哲哉 - 博客园
到此这篇关于C#调用百度地图API根据地名获取经纬度geocoding的文章就介绍到这了,更多相关C#百度地图获取经纬度内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
- 使用C#调用百度地图并实现坐标点的设置以及读取示例
- C#开发Android百度地图手机应用程序(多地图展示)
- 如何根据百度地图计算出两地之间的驾驶距离(两种语言js和C#)
关于使用经纬度得到位置Geocorder和使用经纬度定位的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Android:原生的手机获取经纬度得到当前位置、angular.js codovar之geolocation获取经纬度、C#如何提取经纬度文件中的经纬度数据、C#调用百度地图API根据地名获取经纬度geocoding等相关知识的信息别忘了在本站进行查找喔。
本文标签: