Reputation: 8734
I am trying unsuccessfully to extract the formatted_address property.
The following web service logs the JSON below to the console. I cannot get the formatted address using returnedData.d.results[0].formatted_address
.
$.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(returnedData);
}
});
The format of the json is the exact same as the format over here at Google.
Edit Darin pointed out that I was contradicting myself: the web service wraps up everything in the link above in a d object, I failed to mention that.
Further edit Here is the web service:
[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());
return reader.ReadToEnd();
}
}
and here is 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)
{
alert(returnedData.d[0].results[0].formatted_address);
console.log(returnedData);
}
});
Upvotes: 0
Views: 1166
Reputation: 8734
The answer to this issue turns out to be that the web service is returning a string, instead of json. The built-in javascript serializer does not get used. The eval keyword or something more secure needs to be used. As it happens I ended up using the Google Maps Javascript API and that was much easier anyway.
Upvotes: 0
Reputation: 2578
Have you tried using returnedData.results[0].formatted_address
without the .d.
node. That does not exist!
Upvotes: 1
Reputation: 2894
remove the ".d"
returnedData.results[0].formatted_address
but doing this you are always getting the first node only
Upvotes: 0