简体   繁体   English

如何将地理位置数据从浏览器发送到服务器?

[英]How to send Geolocation data from browser to server?

It seems that I need to run a function on client-side in browser, then send latitude and longitude to server in, for example, an ajax call then use the response data to reflect it on the page? 看来我需要在浏览器的客户端上运行一个函数,然后通过例如ajax调用将纬度和经度发送到服务器,然后使用响应数据将其反映在页面上? So for that I need to add a new endpoint on server side just to manage such requests? 因此,为此,我需要在服务器端添加一个新的端点来管理此类请求? Isn't it possible to get that data from inside the incoming request when a user loads some page? 用户加载某些页面时,是否有可能从传入请求中获取数据?

As you already said yourself, the geolocation is running in Javascript on the client side. 正如您已经说过的那样,地理定位正在客户端的Javascript中运行。 This gets executed when the first request to your server is already finished, the HTML is delivered to the client and the Javascript is executed. 当对服务器的第一个请求已经完成,将HTML交付给客户端并执行Javascript时,将执行此操作。 So no, it is not possible to use the geolocation data with the first request, simply because this data gets executed later. 因此,不能,因为第一个请求不能再使用地理定位数据,因为该数据将在以后执行。

What you can do in your initial request is to use the IP of the user to get at least an approximate geolocation. 在初始请求中,您可以做的是使用用户的IP至少获取大致的地理位置。 I think in general this is a good practice because users may decline or simply ignore to give geolocation data to your website. 我认为一般来说这是一个好习惯,因为用户可能会拒绝或完全忽略将地理位置数据提供给您的网站。 With the IP-based approach you can at least have a fallback solution. 使用基于IP的方法,您至少可以拥有一个后备解决方案。

For geolocation you have two solutions. 对于地理位置,您有两种解决方案。

One is HTML5 geolocation API. 一种是HTML5地理位置API。 If it exists (you can check it with Modernizr), send the location data (the whole location object) to an ajax script on your server along with an user id or what. 如果存在(可以使用Modernizr进行检查),请将位置数据(整个location对象)连同用户ID或其他内容一起发送到服务器上的Ajax脚本。

If the user denies HTML5 geolocation or has an old browser, just use your ajax endpoint again, but with a null location object. 如果用户拒绝HTML5地理位置或使用旧的浏览器,则只需再次使用ajax端点,但使用空位置对象。 Check it server-side, and then if null, check the incoming IP in the headers, then use GeoIP database to locate your user (~40Km-around accuracy). 在服务器端进行检查,如果为null,则检查标头中的传入IP,然后使用GeoIP数据库定位您的用户(准确度约为40Km)。

That way you have a client side js, and a server-side ajax script which work together to locate your user more or less accurately, but always locating ;) 这样,您将拥有一个客户端js和一个服务器端ajax脚本,它们可以一起工作以或多或少地准确定位您的用户,但始终在定位;)

Edit : If you want the incoming geolocation on first page load, just take the incoming IP from the request headers, use GeoIP and get your user geolocation ;-) 编辑:如果要在首页加载时将传入地理位置定位,只需从请求标头中获取传入IP,使用GeoIP并获取用户地理位置;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM