0

Im new to JavaScript and new to combining languages. I want to use geolocation's functions in my Java program and I believe this is the way to do it.

import javax.script.*;

public class Foo{

 public static void main(String[] args) throws Exception {
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        engine.eval(new java.io.FileReader(args[0]));
    }
}


JavaScript

   var navigator ={};

   var locater =  function getLocation() {;
            if (navigator.geolocation) {
             navigator.geolocation.getCurrentPosition(showPosition);
            }
    };
     //tell me how

   locater();

Being new to JavaScript Im not sure how to do this.

I want to get the coordinates and print or possibly make it accessible to the Java program. If I should be using a different way to get my computer's location in a Java application please recommend a method because I cannot find one.

mwong
  • 11
  • 1

1 Answers1

0

A Rhino JavaScript engine running in a Java application is not the same as a JavaScript engine running in a Web Browser. They both interpret JavaScript, but their "services" is where the difference lies.

In a browser, the JavaScript engine may contact a web service to turn an IP address into a latitude-longitude.

In Java, the Rhino engine can access whatever resources the parent Java application has made available to the engine, if any.

To retrieve the current location, the JavaScript code running in Rhino would call a method on a Java object given to the Rhino environment. The Java object would determine the location somehow, and return that to the caller.

If the goal is for your Java application to determine the current location, calling Rhino/JavaScript is not the answer. Instead, use a library such as those listed here: best-way-to-get-geo-location-in-java.

(If desired, you can present this information retrieved by your Java application to Rhino for use in your JavaScript code.)

Community
  • 1
  • 1
AJNeufeld
  • 8,526
  • 1
  • 25
  • 44