Geolocation with javascript

Hi @stucork,

I’m trying to replicate the get location with the JS code.
I would like to fire the location lat, lng not when the loaction updates but over a button.
Each time a button is clicked or function is called the current postion (lat, lng) shoud be send out.
What I’m missing?

<script>
  var geolocator_app = {
    startPolling: function() {
      var form = this; // The jQuery element representing this Form
      if ("geolocation" in navigator) {
        var watchId = navigator.geolocation.getCurrentPosition(function(position) {
          anvil.call(form, 'update_app_position', position.coords.latitude, position.coords.longitude);
        });
        this.data("geoWatch", watchId);
      }
    },
    stopPolling: function() {
      var watchId = this.data("geoWatch");
      if (watchId) {
        navigator.geolocation.clearWatch(watchId);
      }
    }
  };

Hi @Gerhard

As far as I can tell, the form won’t be able to call those methods because they are name spaced
A form can only access functions defined globally i.e.

<script>
    function startPolling() {
        var forrm = this;

    }
</script>

I do typically recommend moving this sort of code to python if possible

from anvil.js.window import navigator
from anvil.js import report_exceptions


class Form1(Form1Template):
    def __init__(self, **properties):
        self._shown = False
        self._watch_id = None
        ....
  
    # hook these up in the designer
    def form_show(self, **event_args):
        if self._shown:
            return
        self._shown = True
        self._watch_id = navigator.geolocation.watchPosition(self.update_app_position)

    def form_hide(self, **event_args):
        self._shown = False
        navigator.geolocation.clearWatch(self._watch_id);

    @report_exceptions
    def update_app_position(self, position, *js_args):
        ...

Hi @stucork,

appprecciate you recommendation and code example.
I tried moving this sort of code to python with no success, did I missed somenthing?
Going back to the js package, this solution worked:

ah yes - namespacing like that is a nice idea.

Maybe you worked out that you needed a Geolocator component to be on the page for the code to work. (you have self.geolocator_1 on the page).
So calling Geolocator().form_show() only works because you had another instance on the screen. The instance needs to be on the screen for the javascript functions to load.

It would probably be better just to call self.geolocator_1.form_show()
And potentially rename this method self.geolocator_1.start_polling()

Here’s the version where everything is in Python

It means you don’t need the component to be on the screen for the code to work.

Hi @stucork,

yes I worked out that the Geolocator component has to be on the page.
Thank you for the “everything is in Python Verison”, great solution, now is clear for me! :+1: