简体   繁体   中英

How to get the address using Latitude and Longitude with gmap?

I have here a Windows Form and when I type the latitude and longitude it wont show the complete address in the richtextbox. Heres my code for the search button:

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);

and heres my code for the form load:

GMaps.Instance.Mode = AccessMode.ServerAndCache;
map.CacheLocation = @"cache";
map.DragButton = MouseButtons.Left;
map.ShowCenter = false;
map.DragButton = MouseButtons.Left;
map.MapProvider = GMapProviders.GoogleMap;

You need to reverse-geocode your coordinates. First, you'll need to add these classes to deserialize the reverse-geocoding response. (The Result class is in the GMap.NET.MapProviders namespace.)

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; }
}

Then you can reverse-geocode the coordinates with an HttpClient, but you'll need a Google API key with the geocoding API enabled first. Get one here if you don't have one.

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();
    }
}

Here are the imports to add to the top of your form class:

using GMap.NET;
using GMap.NET.MapProviders;
using GMap.NET.WindowsForms;
using GMap.NET.WindowsForms.Markers;
using Newtonsoft.Json;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM