2014-09-28 173 views
-1

首先,我使用google map api将地址转换为经度和纬度。我可以将其转换并显示出来。但是,我无法将经纬度设置为隐藏字段,以便我可以使用它来处理......我做了什么错了?谷歌地图api javascript获取经度和纬度?

我可以得到警报

enter image description here

但是......我不能让我设置隐藏字段的值,它表明...

enter image description here

下面是我的代码...

<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> 

<script type="text/javascript"> 

    function sayHello() { 

     // get input address 
     var address = document.getElementById('inputAddress').value; 

     var latitude; 
     var longitude; 

     var geocoder = new google.maps.Geocoder(); 

     geocoder.geocode({ 'address': address }, function (results, status) { 

      if (status == google.maps.GeocoderStatus.OK) { 

       latitude = results[0].geometry.location.lat(); 
       longitude = results[0].geometry.location.lng(); 

     // find hidden field 
     document.getElementById("myLatitudes").value = latitude; 
     document.getElementById("myLongitudes").value = longitude; 

       alert("ShopLatitudes: " + latitude + ", ShopLongitudes: " + longitude); 


      } 

      else 
      { 
       alert("Geocoder failed due to: " + status); 
      } 

     }); 


    } 


</script> 
+1

什么问题?你在哪里打电话?怎么了? – SLaks 2014-09-28 15:13:37

+0

即使设置了隐藏字段,我仍然无法获取经纬度... – 2014-09-28 15:23:49

回答

0

You're sett在表单已经提交之后,异步隐藏隐藏字段。

您只需在异步响应到达后提交表单。

+0

您能否建议我如何修改我的代码?因为我对JavaScript不太好... – 2014-09-28 15:30:41

0

对Google API的调用异步发生。这意味着脚本将继续等待Web服务的反应。只要从webservice收到响应(经度/纬度),就会调用您作为geocode.geocode()的第二个参数传递的回调函数。

因为这需要一段时间,您的脚本已经为隐藏的输入分配了(仍未定义的)经度/纬度值。

要解决这个问题,您应该在您传递给geocoder.geocode()的回调函数中分配经度和纬度。

+0

嗨,感谢您的帮助= D我已经尝试了您的建议。然而,问题仍然存在......我更新了我的代码顶部 – 2014-09-28 15:45:10

+0

您可以添加用于从隐藏字段获取值的代码吗?正如这个plunkr显示的那样,它实际上是正确填写的:http://plnkr.co/edit/aEMYpbLP1UHzpjdTUroB?p=preview – user125661 2014-09-28 15:53:56

+0

你......说得对,但是在我提交表格之后,我无法填写数据。我在服务器端使用Request.Form [“myLatitudes”]。ToString()但没有数据获取... – 2014-09-28 16:04:38

相关问题