当前位置:网站首页>C# Call AutoNavi Map API to obtain latitude, longitude and positioning [Detailed 4D explanation with complete code]
C# Call AutoNavi Map API to obtain latitude, longitude and positioning [Detailed 4D explanation with complete code]
2022-08-11 11:00:00 【Liu Mengfan】
最近有个需求,Positioning is required,I was going to use Baidu MapsAPI定位,But found Baidu map positioning applicationAppKey太麻烦了.Because it is writtenweb端,百度地图定位API申请的AppkeyURL filtering is required.Simply use Gothe to position it(有一说一,Gaode map is really good).话不多说,Let’s first explain some of the details of the positioning implementation that need to be paid attention to.
首先,Regardless of whether you are using AutoNavi or Baidu positioning,都需要获取AppKey.Let's first explain the positioning of GaodeAPPKEY的获取. Use Baidu to locate,百度APPKEYGet the method by Baidu.
1.打开高德地图Appkey申请网址:https://lbs.amap.com/,点击右上角控制台,Then log in and a series of authentications【Just do personal verification,daily quota5000次.If the amount of positioning is large,Then consider taking enterprise certification】.
如下:
认证完成后,Enter the Gaode map console,创建应用分组:

然后创建AppKey:

这就是我们创建的AppKey:

我已经创建了一个,Just use the one created at the beginning to explain.The daily quota of various positioning for individual developers of AutoNavi Maps5000times are completely sufficient.
2.实战代码[Post URL must beHTTPS,因为是web端,最好用谷歌浏览器,The highest positioning accuracy]:
html:
<button type="button" class="layui-btn" id="GPS">获取定位</button>
Js的前端代码:
<script type="text/javascript" scr="http://api.map.baidu.com/api?v=1.2"></script>
<script src="https://cdn.bootcss.com/vConsole/3.2.0/vconsole.min.js"></script>
<script type="text/javascript">
//The browser should be sethttps,否则无响应
var vconsole = new VConsole();
var x_PI = 3.14159265358979324 * 3000.0 / 180.0;
var PI = 3.1415926535897932384626;
var a = 6378245.0;
var ee = 0.00669342162296594323;
$("#GPS").click(function () {
function Location() { };
Location.prototype.getLocation = function (callback) {
var options = {
enableHighAccuracy: true,
maximumAge: 1000
};
this.callback = Object.prototype.toString.call(callback) == "[object Function]" ?
callback :
function (address) {
alert(address.province + address.city);
console.log("getocation(callbackFunction) The positioning information object can be obtained");
};
var self = this;
if (navigator.geolocation) {
//浏览器⽀持geolocation
navigator.geolocation.getCurrentPosition(function (position) {
//经度
var longitude = position.coords.longitude;
//纬度
var latitude = position.coords.latitude;
self.loadMapApi(longitude, latitude);
console.log("经度:" + longitude + ",纬度:" + latitude);
var cons= GpsToGcj02(longitude, latitude);
console.log(cons);
var lng_lat_2 = gcj02tobd09(cons[0], cons[1]);
console.log('百度坐标...', lng_lat_2);
///ajaxRequest a Gaode positioningapi,返回具体位置
let AppKey = "你刚才申请的AppKey";
let lat = cons[0], lng = cons[1], coordsys = "baidu";//经纬度,and the coordinate system type,此处用的是wgs84The rotated Baidu coordinate system,
$.ajax({
url: '@Url.Action("GetLocation")',
type: 'post',
data: { lat:lat,lng:lng,AppKey:AppKey,coordsys:coordsys },
success: function (result) {
if (result.status == "1")
{
console.log(result);
}
}
})
}, self.onError, options);
} else {
//浏览器不⽀持geolocation
alert("浏览器不⽀position");
}
};
Location.prototype.loadMapApi = function (longitude, latitude) {
var self = this;
var oHead = document.getElementsByTagName('HEAD').item(0);
var oScript = document.createElement("script");
oScript.type = "text/javascript";
oScript.src = "http://api.map.baidu.com/getscript?v=2.0&ak=A396783ee700cfdb9ba1df281ce36862&services=&t=20140930184510";
oHead.appendChild(oScript);
oScript.onload = function (date) {
var point = new BMap.Point(longitude, latitude);
var gc = new BMap.Geocoder();
gc.getLocation(point, function (rs) {
var addComp = rs.addressComponents;
self.callback(addComp);
});
}
};
Location.prototype.onError = function (error) {
switch (error.code) {
case 1:
alert("位置服务被拒绝");
break;
case 2:
alert("暂时获取不到位置信息");
break;
case 3:
alert("获取信息超时");
break;
case 4:
alert("未知错误");
break;
}
};
///WGS-84转火星坐标系GCJ02
function GpsToGcj02(lng, lat) {
if (out_of_china(lng, lat)) {
return [lng, lat]
}
else {
var dlat = transformlat(lng - 105.0, lat - 35.0);
var dlng = transformlng(lng - 105.0, lat - 35.0);
var radlat = lat / 180.0 * PI;
var magic = Math.sin(radlat);
magic = 1 - ee * magic * magic;
var sqrtmagic = Math.sqrt(magic);
dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
var mglat = lat + dlat;
var mglng = lng + dlng;
return [mglng, mglat]
}
}
function out_of_china(lng, lat) {
return (lng < 72.004 || lng > 137.8347) || ((lat < 0.8293 || lat > 55.8271) || false);
}
function transformlat(lng, lat) {
var ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
return ret;
}
function transformlng(lng, lat) {
var ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
return ret;
}
//Mars positioning methodGCJ-02转百度BD-09坐标系
function gcj02tobd09(lng, lat) {
var z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_PI);
var theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI);
var bd_lng = z * Math.cos(theta) + 0.0065;
var bd_lat = z * Math.sin(theta) + 0.006;
return [bd_lng, bd_lat]
}
</script>
After the front end obtains the location of the browser,Some can be sent via urlget请求,Check out the positioning effect:
请求地址:https://restapi.amap.com/v3/assistant/coordinate/convert?parameters
AppKeyThe one you applied for yourself,
Then the latitude and longitude is the latitude and longitude sent by the frontend to the backend.When requesting here, separate them with commas,经度在前.
后面的coordsysis the latitude and longitude type.I turned into the interface of the AutoNavi map requested by Baidu positioning,所以填的baidu,
There are several types that can be filled in,Specific reference to GaodeAPI开发者文档,地址:https://lbs.amap.com/api/webservice/guide/api/convert

C#后端代码:
#region Get the relevant interface of user positioning,The front end transmits the Baidu coordinate system,Continue the front-end request after the back-end is transferred to AutoNavi,Get specific location,webMobile terminal is requiredGoogle Chrome 浏览器
public IActionResult GPSIndex()
{
return View();
}
/// <summary>
/// 定位请求,Returns the Gothe coordinate system
/// </summary>
/// <param name="lat">经度</param>
/// <param name="lng">纬度</param>
/// <param name="AppKey">密钥</param>
/// <param name="coordsys">坐标系类型,Baidu coordinate system is used here</param>
/// <returns></returns>
public IActionResult GetLocation(string lat,string lng,string AppKey, string coordsys)
{
var latlng = string.Format(lat + "," + lng);
//Get Gaode positioning
var location = LocationResult(latlng,AppKey,coordsys);
//获取具体位置
var Gps = GetLocationByLngLat(latlng, AppKey, 10000);
return Json(Gps);
}
/// <summary>
/// 根据经纬度获取地址
/// </summary>
/// <param name="lngLatStr">经度纬度组成的字符串 例如:"113.692100,34.752853"</param>
/// <param name="timeout">超时时间默认10秒</param>
/// <returns>失败返回"" </returns>
public static string GetLocationByLngLat(string lngLatStr,string Key,int timeout = 10000)
{
var url = $"http://restapi.amap.com/v3/geocode/regeo?key={Key}&location={lngLatStr}";
return GetLocationByUrl(url, timeout);
}
/// <summary>
/// 根据经纬度获取地址
/// </summary>
/// <param name="lng">经度 例如:113.692100</param>
/// <param name="lat">维度 例如:34.752853</param>
/// <param name="timeout">超时时间默认10秒</param>
/// <returns>失败返回"" </returns>
public static string GetLocationByLngLat(double lng, double lat,string Key, int timeout = 10000)
{
var url = $"http://restapi.amap.com/v3/geocode/regeo?key={Key}&location={lng},{lat}";
return GetLocationByUrl(url, timeout);
}
/// <summary>
/// 根据URL获取地址
/// </summary>
/// <param name="url">Get方法的URL</param>
/// <param name="timeout">超时时间默认10秒</param>
/// <returns></returns>
private static string GetLocationByUrl(string url, int timeout = 10000)
{
var s = "";
try
{
if (WebRequest.Create(url) is HttpWebRequest req)
{
req.ContentType = "multipart/form-data";
req.Accept = "*/*";
req.UserAgent = "";
req.Timeout = timeout;
req.Method = "GET";
req.KeepAlive = true;
if (req.GetResponse() is HttpWebResponse response)
using (var sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
s = sr.ReadToEnd();
return s;
}
}
}
catch (Exception ex)
{
s = ex.ToString();
}
return s;
}
public static GaodeGetCoding LocationResult(string latlng, string AppKey, string coordsys)
{
var url = "https://restapi.amap.com/v3/assistant/coordinate/convert?parameters";
url += string.Format(AppKey, latlng, coordsys);
var Json = GetResponseString(CreateGetHttpResponse(url, null));
var model = JsonConvert.DeserializeObject<GaodeGetCoding>(Json);
return model;
}
/// <summary>
/// 创建GET方式的HTTP请求
/// </summary>
public static HttpWebResponse CreateGetHttpResponse(string url, CookieCollection cookies)
{
HttpWebRequest request = null;
request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.Proxy = null;
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
return request.GetResponse() as HttpWebResponse;
}
/// <summary>
/// 获取请求的数据
/// </summary>
public static string GetResponseString(HttpWebResponse webresponse)
{
using (Stream s = webresponse.GetResponseStream())
{
StreamReader reader = new StreamReader(s, Encoding.UTF8);
return reader.ReadToEnd();
}
}
#endregion
The encapsulation of the return value:
namespace Rongbo.DDPG.Entity.GaoDeLocationAPI
{
public class GaodeGetCoding
{
/// <summary>
/// 返回状态,1=成功,0=失败
/// </summary>
public int Status { get; set; }
/// <summary>
/// 成功编码 OK
/// </summary>
public string Info { get; set; }
public string InfoCode { get; set; }
public List<Gaode> Regeocode { get; set; }
}
public class Gaode
{
public string Formatted_address { get; set; }
public List<GaodeList> AddressComponent { get; set; }
}
public class GaodeList
{
/// <summary>
/// 国籍
/// </summary>
public string Country { get; set; }
/// <summary>
/// 省名
/// </summary>
public string Province { get; set; }
/// <summary>
/// 市名
/// </summary>
public string City { get; set; }
/// <summary>
/// City code
/// </summary>
public string CityCode { get; set; }
/// <summary>
/// Province and county name
/// </summary>
public string district { get; set; }
/// <summary>
/// County code
/// </summary>
public string adCode { get; set; }
/// <summary>
/// 街道名
/// </summary>
public string TownShip { get; set; }
public string TownCode { get; set; }
public List<StreetNumber> StreetNumber { get; set; }
public List<string> BusinessAreas { get; set; }
public List<Building> Building { get; set; }
public List<Neighborhood> Neighborhood { get; set; }
}
public class Neighborhood
{
public string Name { get; set; }
public string Type { get; set; }
}
public class Building
{
public string Name { get; set; }
public string Type { get; set; }
}
public class StreetNumber
{
public List<string> Street { get; set; }
public List<string> Number { get; set; }
public string Location { get; set; }
public List<string> Direction { get; set; }
public List<string> Distance { get; set; }
}
}
前端返回的Json效果【The exact address is hidden by me】:
{“status”:“1”,“regeocode”:{“addressComponent”:{“city”:“杭州市”,“province”:“浙江省”,“adcode”:“330110”,“district”:“余杭区”,“towncode”:“330110012000”,“streetNumber”:{“number”:“359号”,“location”:“119.993782,30.277486”,“direction”:“西北”,“distance”:“41.1047”,“street”:“舒心路”},“country”:“中国”,“township”:“仓前街道”,“businessAreas”:[[]],“building”:{“name”:[],“type”:[]},“neighborhood”:{“name”:[],“type”:[]},“citycode”:“0571”},“formatted_address”:“Cangqian Street, Yuhang District, Hangzhou City, Zhejiang Province**********”},“info”:“OK”,“infocode”:“10000”}
Then after getting it,You can perform a series of operations.
原创不易,After reading, remember to like and favorite.
边栏推荐
- mySQL事务及其特性分析
- logstash/filebeat only receives data from the most recent period
- How to build programming ideas and improve programming ideas
- MySQL约束
- VC6.0 +WDK 开发驱动的环境配置
- 【Ackerman Motion Control】
- Analyzes how Flink task than YARN container memory limit
- MySQL表sql语句增删查改_修改_删除
- mySQL transaction and its characteristic analysis
- 7 天找个 Go 工作,Gopher 要学的条件语句,循环语句 ,第3篇
猜你喜欢

Jetpack Compose学习(9)——Compose中的列表控件(LazyRow和LazyColumn)

你觉得程序员是一个需要天赋的职业吗?

当科学家决定搞点“花里胡哨”的东西

使用.NET简单实现一个Redis的高性能克隆版(七-完结)

Word小技巧之图表实现自动编号和更新

Neuropathic pain classification picture Daquan, neuropathic pain classification

rem如何使用

虚拟机使用 WinSCP & Putty

Convolutional Neural Network Gradient Vanishing, The Concept of Gradient in Neural Networks

安装nodejs
随机推荐
AcWing 273. 分级(线性DP+结论)
PerfView专题 (第一篇):如何寻找热点函数
The crawler is encapsulated into an api
Cholesterol-PEG-FITC, Fluorescein-PEG-CLS, Cholesterol-PEG-Fluorescein water-soluble
[Ext JS]11.14 SimXhr.js?_dc=1659315492151:65 Uncaught TypeError problem analysis and solution
如何给女朋友解释什么是缓存穿透、缓存击穿、缓存雪崩?
VMWare中安装的win10,新增其他盘符,如:E盘,F盘等
VC6.0 +WDK 开发驱动的环境配置
logstash/filebeat only receives data from the most recent period
Neuropathic pain classification picture Daquan, neuropathic pain classification
LeetCode 剑指 Offer 35. 复杂链表的复制
国产数据库有没有在国外的应用案例?
servlet——servlet执行流程 | servlet关系视图
智能恒等于推荐系统
LeetCode每日一题(1754. Largest Merge Of Two Strings)
Install nodejs
mysql常用的一些时间函数记录
chrome is set to dark mode (including the entire webpage)
我用这个操作,代码可读性提升一个档次
[Building a 2D rasterized map using SLAM technology]