问题
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? 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?
回答1:
As you already said yourself, the geolocation is running in Javascript on the client side. 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. 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. 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.
回答2:
For geolocation you have two solutions.
One is HTML5 geolocation 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.
If the user denies HTML5 geolocation or has an old browser, just use your ajax endpoint again, but with a null location object. 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).
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 ;)
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 ;-)
来源:https://stackoverflow.com/questions/16230226/how-to-send-geolocation-data-from-browser-to-server