Ishan
Ishan

Reputation: 1006

Geolocation in scala js

I have following function in my Scala.js program:

def geo():Unit={
  var window = document.defaultView
  val nav = window.navigator
  val geo: Geolocation = nav.geolocation
  def onSuccess(p:Position) = {
   println( s"latitude=${p.coords.latitude}")                // Latitude
   println( s"longitude=${p.coords.longitude}")              // Longitude
  }
  def onError(p:PositionError) = println("Error")
  geo.watchPosition( onSuccess _, onError _ )
}

I am calling this function from my main function. But it is printing the longitude and latitude continuously after some period of time. I wanted to print only one time. I am not able to understand what I am doing wrong here and what should I do to make it stop printing again and again ?

Upvotes: 1

Views: 160

Answers (1)

sjrd
sjrd

Reputation: 22095

You can use clearWatch to stop watching the position as soon as you observed one, like this:

def geo(): Unit = {
  val window = document.defaultView
  val nav = window.navigator
  val geo: Geolocation = nav.geolocation
  var watchID: Int = 0
  def onSuccess(p:Position) = {
    println(s"latitude=${p.coords.latitude}")                // Latitude
    println(s"longitude=${p.coords.longitude}")              // Longitude
    geo.clearWatch(watchID) // only observe one position
  }
  def onError(p:PositionError) = println("Error")
  watchID = geo.watchPosition(onSuccess _, onError _)
}

Upvotes: 1

Related Questions