Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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#?

like image 227
thd Avatar asked Oct 29 '11 22:10

thd


People also ask

Is geocoding API Google free?

The Geocoding API uses a pay-as-you-go pricing model. Geocoding API requests generate calls to one of two SKUs depending on the type of request: basic or advanced.

How do I put Geocodes in Google Maps?

Go to the Google Cloud Console. Click the Select a project button, then select the same project you set up for the Maps JavaScript API and click Open. From the list of APIs on the Dashboard, look for Geocoding API. If you see the API in the list, you're all set.

Can you geocode with Google Maps?

Try Google Maps Platform Forward Geocoding is the process of converting addresses (like a street address) into geographic coordinates (latitude and longitude), which you can use to place markers on a map or position the map.


2 Answers

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

like image 171
L.B Avatar answered Oct 18 '22 11:10

L.B


L.B'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;
    }
like image 34
Sirentec Avatar answered Oct 18 '22 12:10

Sirentec