函数返回undefined

时间:2015-09-29 06:35:56

标签: javascript jquery return

我试图创建一个简单的函数来根据浏览器返回用户位置,但它一直返回undefined:

  function getLocation() {
    //get current location
    var geo_param;
    if(navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        // Create geolocation parameter
        geo_param = "geolocation=[" + position.coords.latitude + "," + position.coords.longitude + "]";
        console.log(geo_param)
      });
    }
    return geo_param
  }

  function search(activity) {
    var searchUrl = "/s?activity=" + activity + "&" + getLocation()
    window.location.href = searchUrl;
    console.info(searchUrl)
  }

2 个答案:

答案 0 :(得分:1)

getCurrentPosition范围是异步的,因此在getCurrentPosition完成运行之前将返回geo_param。解决方法是使用回调,请参阅下面的示例。

 function getLocation(callback, activity) {
     //get current location
     var geo_param;
     if (navigator.geolocation) {
         navigator.geolocation.getCurrentPosition(function (position) {
             // Create geolocation parameter
             geo_param = "geolocation=[" + position.coords.latitude + "," + position.coords.longitude + "]";
             console.log(geo_param);
             callback(geo_param, activity);
         });
     }
 }

 function search(activity) {
     getLocation(search_with_current_location, activity);
 }

 function search_with_current_location(geo_param, activity) {
     var searchUrl = "/s?activity=" + activity + "&" + geo_param;
     window.location.href = searchUrl;
     console.info(searchUrl);
 }

答案 1 :(得分:0)

在这种情况下,您的函数在获取响应之前执行。从<asp:TemplateColumn> <ItemTemplate> <asp:HyperLink runat="server" ID="pageLink" NavigateUrl='<%# "Default.aspx?Pid="+ Eval("pageId") %>' Text='<%# Eval("pageName") %>'></asp:HyperLink> </ItemTemplate> </asp:TemplateColumn> 获得响应后,您需要具有回调函数。

另请注意,重定向网址中没有API geo_param

试试这个:

query string key