oTree Forum >

Recording GPS

#1 by Thair_Ahmad

Is it possible to record location through GPS in a string field in oTree survey?

#2 by Thair_Ahmad

hello everyone, 

Please let me know if there is a way to do this.

#3 by fabsi


I'm not aware that otree supports that out of the box.

However, you could try to use the Geolocation API to achieve what you want.

The following links might be helpful:
- Reference: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API
- Quick start: https://www.w3schools.com/html/html5_geolocation.asp

Keep in mind that the user's browser will ask for permission to report location information.

So here is some code how you could approach this in otree.
If the user allows to share location information the latitude and longitude will be send to the server via the live method and saved to the database.
You could also send an error message to the server, e.g., if the user does not allow to share location information and save that to the database (instead of the latitude/longitude).

Maybe play around with the API whether this can solve your problem and works reliably in your case.
If you have questions, feel free to ask.


{{ block content }}
<input type="button" value="Get Location" onclick="getLocation()">
{{ endblock }}

{{ block scripts }}
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(handleSuccess, handleError);
        } else {

    function handleSuccess(position) {
        let msg = {
            "type": "success",
            "coords": {
                "latitude": position.coords.latitude,
                "longitude": position.coords.longitude

    function handleError(error) {
        liveSend({"type": "error", "error_msg": error.message});

    function handleNotSupported() {
        liveSend({"type": "not_supported"});
{{ endblock }}


class Player(BasePlayer):
    latitude = models.StringField()
    longitude = models.StringField()

class MyPage(Page):

    def live_method(player: Player, data):
        if data['type'] == 'success':
            player.latitude = str(data['coords']['latitude'])
            player.longitude = str(data['coords']['longitude'])
        elif data['type'] == 'error':
            # For example save error instead of coordinates to database
            error_msg = data['error_msg']
            player.latitude = error_msg
            player.longitude = error_msg
        elif data['type'] == 'not_supported':

Write a reply

Set forum username