3

I am trying to call the Google Maps geocoding API, to get a formatted address from a lat/long pair, and then log it to the console. I am trying to get the first 'formatted_address' item that gets returned for a given location. I am simple unable to extract that item from the JSON, I have no idea why. The line of code needed to extract the data would be greatly appreciated.

The javascript:

//Gets the current location of the user
function getLocation()
{
    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(showPosition);
    }

}

function showPosition(position)
{
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;

    $.ajax({
        type: "POST",
        url: "ReportIncident.aspx/ReverseGeocode",
        data: "{latitude:" + latitude + ",longitude:" + longitude + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (returnedData)
        {
         // console.log(/****formatted_address Here Please****/);
        }
    });
}

The C#:

        [WebMethod]
        public static string ReverseGeocode(decimal latitude, decimal longitude)
        {
            // Create the web request  

            string url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude +
                         "&sensor=true";
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            // Get response  
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                // Get the response stream  
                StreamReader reader = new StreamReader(response.GetResponseStream());

                // Console application output  
                return reader.ReadToEnd();
            }
        }
5
  • I am myself not sure about it, but are you sure you should be using POST? Commented Jul 3, 2012 at 15:37
  • @John, the data gets returned alright, I just can't extract it. Commented Jul 3, 2012 at 15:39
  • @lee can you show us the JSON string being returned, please? Commented Jul 3, 2012 at 15:45
  • @Ohgodwhy it is the same as the data from maps.googleapis.com/maps/api/geocode/…, but it is wrapped in the "d" element, as is standard with the above type of web service. Commented Jul 3, 2012 at 15:47
  • stackoverflow.com/questions/11166355/… Commented Jul 3, 2012 at 15:58

2 Answers 2

2

Your JSON is escaped because you're returning a string from your WebMethod, and not letting the built in JavascriptSerializer do it's thing.

roughly, you're seeing this:

"\{ /*data*/ \}"

instead of this:

{ /*data*/ }

You can fix this by running the returned string through eval() but note that I'm not recommending it... just saying you can

EDIT:

 $.ajax({
    type: "POST",
    url: "ReportIncident.aspx/ReverseGeocode",
    data: "{latitude:" + latitude + ",longitude:" + longitude + "}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (returnedData)
    {
        var realReturnedData = eval(returnedData.d);
        //realReturnedData now has the google maps data structure you're expecting
    }
});

Again... eval is evil (if you don't 100% trust the source). I would recommend returning a different data type from your webmethod...

EDIT 2:

[WebMethod]
public static MyClass ReverseGeocode(decimal lat, decimal long) {
   MyClass obj = new MyClass();
   //do stuff
   return obj;
}

But my real question is why are you doing this with a webservice call to your server? You can directly do geocoding from Javascript to google's API https://google-developers.appspot.com/maps/documentation/javascript/examples/geocoding-reverse

Sign up to request clarification or add additional context in comments.

4 Comments

I think you are right, but how do I let the built-in javascript serializer do its thing.
There's nothing wrong with using eval if you trust the source.
@rossisdead: True enough. I haven't found a case where it's been necessary, though in my line of work. The point is to refactor and not use it if possible. Given the automatic serialization ASMX/ASPX webmethods offer, it certainly isn't necessary here if using a complex (user-defined) return type (which would also open that method up to being useful for other parts of the server-side code).
@BLSully thanks, I used the javascript API, and that solved everything. The returning a string and not use the javascript serializer was also 100% correct.
0

I think the API returns something like:

{
    "results" : [
    {
        "address_components" : [/***/],
        "formatted_address": "..."
        /* other */
    }],
    "status" : "OK"
}

You could try:

if(returnedData.results.length > 0) {
    console.log(returnedData.results[0].formatted_address);
}

EDIT: Take a look at the API documentation https://developers.google.com/maps/documentation/geocoding/

3 Comments

I keep getting this error: Uncaught TypeError: Cannot read property '0' of undefined, even though data is being returned.
@lee: Now am beginning to wonder if you are actually receiving the EXPECTED data
I am getting the correct data: it is returning my address, I just cannot get it from the JSON.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.