[英]How to get the address using Latitude and Longitude with gmap?
我在這里有一個Windows窗體,當我輸入緯度和經度時,它不會在richtextbox中顯示完整的地址。 這是我的搜索按鈕代碼:
double lat = Convert.ToDouble(textBox8.Text);
double longt = Convert.ToDouble(textBox6.Text);
map.Position = new PointLatLng(lat, longt);
map.MinZoom = 5;
map.MaxZoom = 100;
map.Zoom = 10;
PointLatLng point = new PointLatLng(lat, longt);
GMapMarker marker = new GMarkerGoogle(point, GMarkerGoogleType.blue_dot);
GMapOverlay markers = new GMapOverlay("markers");
markers.Markers.Add(marker);
map.Overlays.Add(markers);
這是我的表單加載代碼:
GMaps.Instance.Mode = AccessMode.ServerAndCache;
map.CacheLocation = @"cache";
map.DragButton = MouseButtons.Left;
map.ShowCenter = false;
map.DragButton = MouseButtons.Left;
map.MapProvider = GMapProviders.GoogleMap;
您需要對坐標進行反向地理編碼。 首先,您需要添加這些類以反序列化反向地理編碼響應。 (Result類位於GMap.NET.MapProviders命名空間中。)
public class ReverseGeocodeResult
{
public PlusCode plus_code { get; set; }
public List<Result> results { get; set; }
public string status { get; set; }
}
public class PlusCode
{
public string compound_code { get; set; }
public string global_code { get; set; }
}
然后,您可以使用HttpClient對坐標進行反向地理編碼,但是您需要先啟用地理編碼API的Google API密鑰。 如果您沒有一本,請在這里買一本。
using (var c = new HttpClient())
{
try
{
var result = await c.GetAsync("https://maps.googleapis.com/maps/api/geocode/json?latlng="
+ lat.ToString() + "," + longt.ToString() + "&key=YOUR_API_KEY");
string content = await result.Content.ReadAsStringAsync();
ReverseGeocodeResult results = JsonConvert.DeserializeObject<ReverseGeocodeResult>(content);
if (results != null && results.results.Count > 0)
richTextBox1.Text = results.results[0].formatted_address;
}
catch (Exception exc)
{
richTextBox1.Text = exc.ToString();
}
}
這是要添加到表單類頂部的導入:
using GMap.NET;
using GMap.NET.MapProviders;
using GMap.NET.WindowsForms;
using GMap.NET.WindowsForms.Markers;
using Newtonsoft.Json;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.