如何将地理定位变量从客户端传递到服务器端

时间:2013-09-03 12:54:12

标签: javascript django html5 google-maps geolocation

一旦用户允许使用他的地理位置,有人可以建议我将一个客户端Java脚本位置变量(lat,lng)传递给我的服务器端的方法。这样我就可以使用location变量来查询我的数据库,查找10公里范围内的商店,并将它们显示在地图上。

我在客户端使用HTML5 Geolocation获取用户位置,在服务器端使用Django + PostGIS数据库进行距离查找。

1 个答案:

答案 0 :(得分:2)

为了在用户允许使用Geolocation时将用户Geolocation从客户端传递到服务器端,请

  1. 将用户位置变量(pos)分配给HTML元素(位置)
  2. 然后,自动提交包含POST方法的HTML表单。
  3. 以上代码都必须在Google Geolocation API中编写,如下面的摘录所示。

    var infowindow = new google.maps.InfoWindow({
        map: map,
        position: pos,
        content: 'Location found using HTML5.'
      });
      // the below line has been inserted to assign a JS variable to HTML input field called 'geolocation'
    document.getElementById('location').value = pos
      map.setCenter(pos);
    // the below line has been inserted to autosubmit the form.  
    document.getElementById("geolocation").submit(); 
    

    以下是HTML表单

    <form id = "geolocation" action="/location" method="POST" >
                {% csrf_token %}
            <input type="text" id = "location" name="location" value="" />
            <input type="submit" />
    
    </form>