Tag Archives: javascript

Javascript Engine in Java

Yes you can create your own javascript engine in Java. This is a cool feature I never knew existed. I don’t know how long it’s been around, I’m guessing Java 6.

Basically, you can do something like this:

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class JavaJS {

  public static void main(String[] args) throws ScriptException {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    String script = 
        "function sayHello(name) {"
      + "  print('Hello ' + name);"
      + "}"
      + "sayHello('tom');";
    engine.eval(script);
  }

}

And it will print Hello tom.

You can even mix and match Java and Javascript, here’s how to have Java calling the Javascript function above:

Invocable invocable = (Invocable) engine;
invocable.invokeFunction("sayHello", "Jim");

Cool eh? Read more about this on the Oracle’s Java Scripting Programmer Guide or google JSR-223.

Showing Geographical Location On Google Map (Geocoding)

Translating a geographical location such as “London, UK” into a lat/long coordinate (lat: 51.5085150, long: -0.1254870) is called geocoding. This coordinate can then be used to display the location on google map.

Try putting a location in the box below and hit go:

Register for Google Map API Key

In order to implement the above widget first obtain an API key from Google:

  1. Go to
  2. Select Services on the left menu, ensure Geocoding API, Google Maps Embed API and Google Maps JavaScript API v3 are turned on

    geocoding1

    geocoding2
  3. Go to API Access, select Create new Browser key

    geocoding3
  4. The list of accepted HTTP referers will be asked, if you’re testing on local machine this would probably be localhost/*, otherwise you need to put your website domain name here. Hit Create once you’re done

    geocoding4
  5. Take a note of your API key, this will be used in the later part of this tutorial

    geocoding5

The HTML Code

This widget only contains 3 elements:

  • A text input box to provide the geographical location
  • A button to submit the address and show it on the map
  • A div container for the map
Enter location (eg: London, UK): 


Javascript

2 javascript libraries are used: jQuery and Google Map JS. The key parameter on the Google Map JS URL should be the key created above.


Firstly let’s initialize the div container so it doesn’t come up with blank map, here I set it into coordinate of San Francisco, CA:

$(document).ready(function() {
        var map = new google.maps.Map($('#map')[0], {
                center: new google.maps.LatLng(37.7749295, -122.4194155),
                zoom: 8
        });
        ...
}

And create a click handler for the ‘Go’ button which sends ajax post into Google Map JS API. The API will return a JSON response with the location if successful.

$(document).ready(function() {
        ...
        $('#go').click(function(e) {
                e.preventDefault();
                var loc = $('#loc').val();
                $.ajax({
                        url: '//maps.googleapis.com/maps/api/geocode/json?sensor=false&address='+loc
                }).done(function(data) {
                        if(data.status != "OK") {
                                alert("Unable to find location");
                                return;
                        }
                        var loc_result = data.results[0].geometry.location;
                        map.setCenter(new google.maps.LatLng(loc_result.lat, loc_result.lng));
                });
        });
});

See the widget in action in full screen.