Search code examples
gwtjsni

How do we create a JavaScript object in a native method?


I'm working with the google maps api, I'd like to create an instance of one of their objects:

public static final native void test(double lat, double lng) /*-{
    var obj = new google.maps.LatLng(lat, lng);
}-*/; 

but the above does not work, prints the following error:

com.google.gwt.core.client.JavaScriptException: (ReferenceError)
@com.google.gwt.core.client.impl.Impl::apply
    (Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)
    ([JavaScript object(4), JavaScript object(3), JavaScript object(6)]): 
    google is not defined

so I probably have to explain to GWT what the "google.maps.LatLng" object is - how do I do that? I thought there was a specific syntax for that, but can't seem to find it anymore in the docs,

Thanks


Solution

  • If you define google.maps somewhere else in your host page, you must prefix it with $wnd in your GWT code:

    public static final native void test(double lat, double lng) /*-{
        var obj = new $wnd.google.maps.LatLng(lat, lng);
    }-*/;
    

    From GWT documentation:

    When accessing the browser's window and document objects from JSNI, you must reference them as $wnd and $doc, respectively. Your compiled script runs in a nested frame, and $wnd and $doc are automatically initialized to correctly refer to the host page's window and document.