我正在尝试调用Google Maps地理编码API,从lat / long对获取格式化地址,然后将其记录到控制台。我正在尝试获取为给定位置返回的第一个'formatted_address'项。 我很简单无法从JSON中提取该项,我不知道为什么。提取数据所需的代码行将不胜感激。
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****/);
}
});
}
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();
}
}
答案 0 :(得分:2)
您的JSON已转义,因为您从WebMethod
返回了一个字符串,而不是让内置的JavascriptSerializer
执行此操作。
粗略地说,你看到了这个:
"\{ /*data*/ \}"
而不是:
{ /*data*/ }
您可以通过eval()
运行返回的字符串来解决此问题,但请注意我不推荐它...只是说你可以
修改强>:
$.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
}
});
再次...... eval是邪恶的(如果你不100%信任来源)。我建议您从webmethod中返回不同的数据类型......
编辑2 :
[WebMethod]
public static MyClass ReverseGeocode(decimal lat, decimal long) {
MyClass obj = new MyClass();
//do stuff
return obj;
}
但我真正的问题是你为什么要通过web服务调用你的服务器呢?您可以直接从Javascript到Google的API https://google-developers.appspot.com/maps/documentation/javascript/examples/geocoding-reverse
进行地理编码答案 1 :(得分:0)
我认为API返回的内容如下:
{
"results" : [
{
"address_components" : [/***/],
"formatted_address": "..."
/* other */
}],
"status" : "OK"
}
你可以尝试:
if(returnedData.results.length > 0) {
console.log(returnedData.results[0].formatted_address);
}
编辑:请查看API文档https://developers.google.com/maps/documentation/geocoding/