我尝试了一个隐藏的字段控件,但它没有将javascript值返回给c#后面的代码。当我执行下面的代码时,它总是返回0.
如何获取从javascript到c#的距离值?
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function GetDistance()
{
var origin = document.getElementById("orig").value,
destination = document.getElementById("dest").value,
service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
avoidHighways: false,
avoidTolls: false
},
callback
);
function callback(response, status) {
alert('hello2');
var orig = document.getElementById("orig"),
dest = document.getElementById("dest"),
dist = document.getElementById("dist");
if (status == "OK") {
orig.value = response.originAddresses[0];
dest.value = response.destinationAddresses[0];
dist.value = response.rows[0].elements[0].distance.text;
document.getElementById('<%=hdnResultValue.ClientID%>').value = dist.value;
} else {
alert("Error: " + status);
}
}
}
</script>
<form id="frm1" runat="server" method="post">
<br>
Basic example for using the Distance Matrix.<br><br>
Origin: <input id="orig" type="text" style="width:35em"><br><br>
Destination: <input id="dest" type="text" style="width:35em"><br><br>
Distance: <input id="dist" type="text" style="width:35em">
<asp:Button ID="btnSubmit" runat="server" Text ="Submit Application" OnClientClick="GetDistance();" OnClick="btnSubmit_Click" />
<asp:Label ID="lblDistance" runat="server" Text=" " />
<asp:HiddenField ID="hdnResultValue" Value="0" runat="server" />
</form>
protected void btnSubmit_Click(object sender, EventArgs e)
{
lblDistance.Text = hdnResultValue.Value;
lblDistance.Text += "Calculated Successfully";
}
答案 0 :(得分:0)
请参阅Distance Matrix Service Specification。
该方法仅返回一个 DistanceMatrixResponse 对象。如果您想要请求的状态,则必须解析链接页面上显示的已接收JSON元素:rows [index] .elements.status。
{
"origin_addresses": [ "Greenwich, Greater London, UK", "13 Great Carleton Square, Edinburgh, City of Edinburgh EH16 4, UK" ],
"destination_addresses": [ "Stockholm County, Sweden", "Dlouhá 609/2, 110 00 Praha-Staré Město, Česká republika" ],
"rows": [ {
"elements": [ {
"status": "OK",
"duration": {
"value": 70778,
"text": "19 hours 40 mins"
},
"distance": {
"value": 1887508,
"text": "1173 mi"
}
}, {
"status": "OK",
"duration": {
"value": 44476,
"text": "12 hours 21 mins"
},
"distance": {
"value": 1262780,
"text": "785 mi"
}
} ]
}, {
"elements": [ {
"status": "OK",
"duration": {
"value": 96000,
"text": "1 day 3 hours"
},
"distance": {
"value": 2566737,
"text": "1595 mi"
}
}, {
"status": "OK",
"duration": {
"value": 69698,
"text": "19 hours 22 mins"
},
"distance": {
"value": 1942009,
"text": "1207 mi"
}
} ]
} ]
}