简体   繁体   中英

Google Maps v3 geocoding server-side

I'm using ASP.NET MVC 3 and Google Maps v3. I'd like to do geocoding in an action. That is passing a valid address to Google and getting the latitude and longitude back. All online samples on geocoding that I've seen have dealt with client-side geocoding. How would you do this in an action using C#?

I am not sure if I understand you correctly but this is the way I do it (if you are interested)

void GoogleGeoCode(string address)
{
    string url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=true&address=";

    dynamic googleResults = new Uri(url + address).GetDynamicJsonObject();
    foreach (var result in googleResults.results)
    {
        Console.WriteLine("[" + result.geometry.location.lat + "," + result.geometry.location.lng + "] " + result.formatted_address);
    }
}

using the extension methods here & Json.Net

LB's solution worked for me. However I ran into some runtime binding issues and had to cast the results before I could use them

 public static Dictionary<string, decimal> GoogleGeoCode(string address)
    {
        var latLong = new Dictionary<string, decimal>();

        const string url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=true&address=";

        dynamic googleResults = new Uri(url + address).GetDynamicJsonObject();

        foreach (var result in googleResults.results)
        {
            //Have to do a specific cast or we'll get a C# runtime binding exception
            var lat = (decimal)result.geometry.location.lat;
            var lng = (decimal) result.geometry.location.lng;

            latLong.Add("Lat", lat);
            latLong.Add("Lng", lng);
        }

        return latLong;
    }

I ran into issues due to the new Google API requirement to use a valid API Key. To get things working I modified the code to append the key to the address and changing the url to https :

public Dictionary<string, decimal> GoogleGeoCode(string address)
{
    var latLong = new Dictionary<string, decimal>();
    string addressReqeust = address + "&key=your api key here";
    const string url = "https://maps.googleapis.com/maps/api/geocode/json?sensor=true&address=";

    dynamic googleResults = new Uri(url + addressReqeust).GetDynamicJsonObject();

    foreach (var result in googleResults.results)
    {
        //Have to do a specific cast or we'll get a C# runtime binding exception
        var lat = (decimal)result.geometry.location.lat;
        var lng = (decimal)result.geometry.location.lng;
        try
        {
            latLong.Add("Lat", lat);
            latLong.Add("Lng", lng);
        }
        catch (Exception ex)
        {

        }
    }

    return latLong;
}

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