如何将javascript警报消息值传递给asp.net中的标签

时间:2016-01-31 16:25:09

标签: javascript jquery asp.net

我实现了地理位置,其中浏览器获取用户的位置。 在此代码中,我通过浏览器获取用户的地理位置,但它使用javascript警报消息显示位置。

我只想将警报消息值传递给ASP.Net&中的标签或隐藏字段。不想运行警报消息

我的javascript代码如下。

<script type="text/javascript">
     var geocoder;

     if (navigator.geolocation) {
         navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
     }
     //Get the latitude and the longitude;
     function successFunction(position) {
         var lat = position.coords.latitude;
         var lng = position.coords.longitude;
         codeLatLng(lat, lng)
     }

     function errorFunction() {
         alert("Geocoder failed");
     }

     function initialize() {
         geocoder = new google.maps.Geocoder();
     }

     function codeLatLng(lat, lng) {

         var latlng = new google.maps.LatLng(lat, lng);
         geocoder.geocode({ 'latLng': latlng }, function (results, status) {
             if (status == google.maps.GeocoderStatus.OK) {
                 console.log(results)
                 if (results[1]) {
                     //formatted address
                     alert(results[0].formatted_address)
                     //find country name
                     for (var i = 0; i < results[0].address_components.length; i++) {
                         for (var b = 0; b < results[0].address_components[i].types.length; b++) {

                             //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
                             if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
                                 //this is the object you are looking for
                                 city = results[0].address_components[i];
                                 break;
                             }
                         }
                     }
                     //city data
                     alert(city.short_name + " " + city.long_name)
                      document.getElementById('<%=Label1.ClientID %>').innerHTML = city;

                 } else {
                     alert("No results found");
                 }
             } else {
                 alert("Geocoder failed due to: " + status);
             }
         });
     }
</script> 

1 个答案:

答案 0 :(得分:0)

如果要将值存储在隐藏字段中,请替换

alert(results[0].formatted_address)

//hdnField is the ID of your asp:HiddenField object
var hiddenField = document.getElementById("<%= hdnField.ClientID %>")
hiddenField.value = results[0].formatted_address;