Code Monkey home page Code Monkey logo

gwty-leaflet's Introduction

Build Status

Maven Central

Overview

gwty-leaflet is wrapper for the famous maps javascript library Leaflet. gwty-leaflet is based on JsInterop and allows using Leaflet from your GWT application exactly the same way as from a javascript script with a slight advantage: static typing. It was partially generated automatically from Leaflet docs.

Dependency

                     <dependency>
                        <groupId>com.gwidgets</groupId>
                        <artifactId>gwty-leaflet</artifactId>
                        <version>{version}</version>
                     </dependency>

If you are using a snaphost version, then you need to include the snapshot repository:

<repositories>
		<repository>
			<id>snapshots</id>
			<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
			<releases>
				<enabled>false</enabled>
			</releases>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>
	</repositories>

Also, do not forget to include gwty-leaflet in your .gwt.xml module definition file:

 <inherits name='com.gwidgets.api.GwtyLeaflet' />
                  

Versions

  • 1.1.1 (exceptional): intoduces a small fix for LayerGroup eachLayer method.
  • 1.1 (exceptional): fixes a number of shortcomings and issues related mainly related to GeoJSON (checkout release page for more details)
  • 1.0: latest stable version, compatible with leaflet 1.0 and 1.0.1, uses Elemental 2
  • 0.5: compatible with leaflet 1.0
  • 0.4: compatible with leaflet 0.7

Leaflet javascript files:

As in any JsInterop wrapper, you need to refer to the Javascript files from your .html app file. You can either download the Js files from Leaflet website, or refer to them directly using their cdn (there are performance implications off course!).

<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>

Starting from the version 0.5, a new feature has been added to allow adding leaflet resource files dynamically from the code instead of including them manually in the .html:

LeafletResources.whenReady(false, 
        e -> 
                 {
      MapOptions options = new MapOptions.Builder(L.latLng(52.51, 13.40), 12.0, 12.0).dragging(false).build();
    final Map map = L.map("map", options);
    GWT.log(options.getZoom()+"");
    L.tileLayer(MAP_URL, null).addTo(map);
     return null;
    });

If the debug flag is set to false, Leaflet minified .js file will be injected, if set to true the unminified version will injected(leaflet-src.js).

This will automatically inject the leaflet .js and .css, and execute the code inside when they are loaded.

Initializing objects

All objects initializations are done through the L class. gwty-leaflet provides all factory methods of Leaflet. For example:

//equivalent to new Map(...)
Map map = L.map("map", new MapOptions.Builder().build());

//equivalent to new Circle(...)
Circle circle = L.circle(L.latLng(51.508, 11), 200, options);

For more information about Leaflet objects creational patterns, you can refer to Leaflet's official documentation.

Options

As specified by Leaflet documentation, the creation of some objects requires a set of options. gwty-leaflet provides all the options with their respective default values as Objects annotated with @JsType. As of version 0.4, options builders were introduced to help in the creation of option Objects and enforce fields validations. Several options have required fields, and using builders help the developer distinguish between required and optional fields.

Before version 0.4:

              PathOptions options = new PathOptions();
                options.fillColor = "#fff";
                options.opacity = 1;

                //...

                L.circle(L.latLng(51.508, 11), 200, options).addTo(map);

After version 0.4:

              PathOptions options = new PathOptions.Builder()
                                     .fillColor("#fff")
                                     .opacity(1)
                                      .build();

                //...

                L.circle(L.latLng(51.508, 11), 200, options).addTo(map);

For more informations about the available options for each objects, and their utility. You can refer to the original leaflet documentation.

Example

To create a map in a div with an id="map", we can do something like:

                
                L.map("map", new MapOptions.Builder().build()).setView(L.latLng(51.505, -0.09), 12.0, new ZoomPanOptions.Builder().build());

Events

Events are available only in some objects. Events can be handled throught the following methods: clearAllEventListeners(), on(String type, Function fn), once(String type, Function fn), off(String type, Function fn), fire(String type).

For defining actions, events needs to be supplied with an abstract callback function that needs to be implemented by the developer. The below example will dipslay a pop up on each map click:

map.on(EventTypes.MapEvents.CLICK, new EventCallback<MouseEvent>() {
			@Override
			public void call(MouseEvent event) {
                                
                                map.openPopup("hello", msEvent.getLatlng(), new PopupOptions.Builder().build());
                                return null;
                        }
                        
                });

Event Objects are:

  • DragEndEvent
  • ErrorEvent
  • GeoJSONEvent
  • KeyboardEvent
  • LayersControlEvent
  • LayerEvent
  • LocationEvent
  • MouseEvent
  • PopupEvent
  • ResizeEvent
  • TileErrorEvent
  • TileEvent
  • TooltipEvent

Events are executed following the order of registration.

Events are explained in details in Leaflet's documentation.

Events types constants

There is a long list of available events for some objects, and the developer may not know what events are available for the object they are using. The EventType class contains a list of subclasses which contains the available events types constants. The event type can be accessed in static a way like: EventTypes.{object name}Events.{event type name}. For example, to register the loading event on a TileLayer :

tile.on(EventTypes.TileLayer.LOADING, new EventCallback<TileEvent>() {
			@Override
			public void call(TileEvent event) {
                        //do something
                        }
                        
                });

Here is a list of the events that can be registred for objects that can handle events:

Object Available Events
DivOverlayEvents add, remove, popupopen, popupclose, tooltipopen, tooltipclose
RendererEvents update, add, remove, popupopen, popupclose, tooltipopen, tooltipclose
InteractiveLayerEvents click, dblclick, mousedown, mouseover, mouseout, contextmenu, add, remove, popupopen, popupclose, tooltipopen, tooltipclose
LayerEvents add, remove, popupopen, popupclose, tooltipopen, tooltipclose
PosAnimationEvents start, step, end
DivIconEvents add, remove, popupopen, popupclose, tooltipopen, tooltipclose
IconEvents add, remove, popupopen, popupclose, tooltipopen, tooltipclose
GridLayerEvents loading, tileunload, tileloadstart, tileerror, tileload, load, add, remove, popupopen, popupclose, tooltipopen, tooltipclose
GeoJsonEvents layeradd, layerremove, add, remove, popupopen, popupclose, tooltipopen, tooltipclose
FeatureGroupEvents layeradd, layerremove, add, remove, popupopen, popupclose, tooltipopen, tooltipclose
LayerGroupEvents add, remove, popupopen, popupclose, tooltipopen, tooltipclose
CanvasEvents update, add, remove, popupopen, popupclose, tooltipopen, tooltipclose
SVGEvents update, add, remove, popupopen, popupclose, tooltipopen, tooltipclose
CircleMakerEvents click, dblclick, mousedown, mouseover, mouseout, contextmenu, add, remove, popupopen, popupclose, tooltipopen, tooltipclose
CircleEvents click, dblclick, mousedown, mouseover, mouseout, contextmenu, add, remove, popupopen, popupclose, tooltipopen, tooltipclose
RectangleEvents click, dblclick, mousedown, mouseover, mouseout, contextmenu, add, remove, popupopen, popupclose, tooltipopen, tooltipclose
PolygonEvents click, dblclick, mousedown, mouseover, mouseout, contextmenu, add, remove, popupopen, popupclose, tooltipopen, tooltipclose
PolylineEvents click, dblclick, mousedown, mouseover, mouseout, contextmenu, add, remove, popupopen, popupclose, tooltipopen, tooltipclose
PathEvents click, dblclick, mousedown, mouseover, mouseout, contextmenu, add, remove, popupopen, popupclose, tooltipopen, tooltipclose
ImageOverlayEvents click, dblclick, mousedown, mouseover, mouseout, contextmenu, add, remove, popupopen, popupclose, tooltipopen, tooltipclose
TileLayerWMSEvents loading, tileunload, tileloadstart, tileerror, tileload, load, add, remove, popupopen, popupclose, tooltipopen, tooltipclose
TileLayerEvents loading, tileunload, tileloadstart, tileerror, tileload, load, add, remove, popupopen, popupclose, tooltipopen, tooltipclose
TooltipEvents add, remove, popupopen, popupclose, tooltipopen, tooltipclose
PopupEvents add, remove, popupopen, popupclose, tooltipopen, tooltipclose
MarkerEvents move, dragstart, movestart, drag, dragend, moveend, click, dblclick, mousedown, mouseover, mouseout, contextmenu, add, remove, popupopen, popupclose, tooltipopen, tooltipclose
MapEvents baselayerchange, overlayadd, overlayremove, layeradd, layerremove, zoomlevelschange, resize, unload, viewreset, load, zoomstart, movestart, zoom, move, zoomend, moveend, popupopen, popupclose, autopanstart, tooltipopen, tooltipclose, click, dblclick, mousedown, mouseup, mouseover, mouseout, mousemove, contextmenu, keypress, preclick, zoomanim, locationerror, locationfound

Javadoc :

Elemental 2:

The 1.0 version makes use of Elemental 2, instead of local javascript wrapped Elements(under .elemental package). The .elemental package has been removed as it is not needed anymore.

GWT version:

the 0.5 version is compiled using GWT 2.8.0. the 1.0 version is compiled using GWT 2.8.2.

gwty-leaflet's People

Contributors

bykka avatar olivergg avatar tyler-ham avatar zak905 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gwty-leaflet's Issues

Point is missing z (zoom)

Point is missing the z property - used in TileEvent.getCoords() - "Point object with tile's x, y, and z (zoom level) coordinates"

@JsProperty
public double z;

LeafletResources path

Can I recommend using GWT.getModuleBaseForStaticFiles() instead of GWT.getModuleName() in LeafletResources? In my case, my page was not the root.. eg /some/path which resulted in LeafletResources looking for /some/path/gwt_module_name/leaflet/leaflet.js.

Using GWT.getModuleBaseForStaticFiles(), LeafletResources instead looks for /gwt_module_name/leaflet/leaflet.js as expected

Compile failure path for type 'com.gwidgets.api.client.GwtyLeaflet

I compiled gwty-leaflet to a jar file using maven and then added that jar to the build path of a simple test project that I created (with Eclipse). The project is using GWT 2.8.0.beta1 and is the standard GWT "greet". The project works fine until I add an inherits for GwtyLeaflet.

After adding an element to the app's gwt.xml file the following error is displayed at compile time...

Do you have any suggestion as to what the problem could be? The jar is on the build path, as is gwt-material-1.5.3.jar, gwt-material-addins-1.5.2.jar and gwt-material-themes-1.5.2.jar.

Finding entry point classes
Tracing compile failure path for type 'com.gwidgets.api.client.GwtyLeaflet'
Checked 0 dependencies for errors.
[ERROR] Hint: Check that the type name 'com.gwidgets.api.client.GwtyLeaflet' is really what you meant
[ERROR] Hint: Check that your classpath includes all required source roots

Issue initializing tile layer

Hi,
With the latest snapshot when i try to bootstrap the map i see only gray background. Then I noticed in the leaflet quick start tutorials I need to initialize tile layer which than gives javascript error saying id is not defined.
Is there any startup project that can show an actual map without gray area, for the latest leaflet version?
Thanks.

String tileUrl = "https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=XXX"; LatLng center = L.latLng(41.130076, 29.256913); Map map = L.map("map", new MapOptions.Builder(center,13,5).build()); L.tileLayer(tileUrl, new TileLayerOptions.Builder().build()).addTo(map);

Issue creating map with HTMLPanel

I have the following code.

public class MapWidget {

    Map itsMap;
    public MapWidget(HTMLPanel inHTMLPanel) {
        LatLng center = L.latLng(0, 0);
        HTMLElement mapElement = new HTMLElement();
        mapElement.innerHTML = inHTMLPanel.getElement().getInnerHTML();
        itsMap = L.map(mapElement, new MapOptions.Builder(center, 1, 1).build());
    }
    public HTMLElement getElement(){
        return itsMap.getContainer();
    }
}

I get the following error in my console.

MapWidget.java:21 Uncaught TypeError: Cannot read property 'gwidgets' of undefined

The line the it complains about is
HTMLElement mapElement = new HTMLElement();

I believe it has to use a builder to create that but looking at what is available from L class there doesn't seem to be one.

I was following what was done in the following issue #2

Any help would be greatly appreciated.

JSNI vs jsinterop

How come there is still some JSNI usage in gwty-leaflet/src/main/java/com/gwidgets/api/leaflet/events/Event.java ?
Does this mean there is still work to be done to fully migrate to jsinterop ?

1.1 geometry MultiLineString, LineString

Hi,
in my geoJson string I have some MultilineString geometry. But when I am generating JsObject:
(JsObject) Global.JSON.parse(jsonString);
Something is wrong. Am I missing something? When I have Multipolygon It is ok...
Thanks

Interop for some Leaflet plugins

Would it be ok to add to this project some interop files for some well known Leaflet plugin such as Leaflet.ClusterMarker and Leaflet.Draw ? Or should it be put in new separate libraries ?

How to use an htmlpanel to initialize a map

There are two APIs L.map to initialize map. One takes String id and other takes HTMLElement.
How can I use HTMLPanel widget here. I think if you can provide HTMLElement class extending JavaScriptObject then HTMLPanel::getElement can be used here.

Problem with TileLayerOptions.

When you try to use TileLayerOptions as argument 'options' of L.tileLayer method (otherwise of null)

LeafletResources.whenReady( e -> {
    MapOptions options = new MapOptions.Builder(L.latLng(52.51, 13.40), 5.0, 5.0).dragging(false).build();
    final Map map = L.map("map", options);
    TileLayerOptions tloptions = new TileLayerOptions.Builder().attribution("test").build();
    L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", tloptions).addTo(map);
    return null;
});

this provide next JavaScript error:

Uncaught TypeError: Cannot read property 'appendChild' of undefined
    at e._initContainer (leaflet.js:6)
    at e.onAdd (leaflet.js:6)
    at e._layerAdd (leaflet.js:6)
    at e.whenReady (leaflet.js:6)
    at e.addLayer (leaflet.js:6)
    at e.addTo (leaflet.js:6)
    at ENd_g$ (Main.java:31)
    at Function.LNd_g$ (Main.java:17)
    at HTMLScriptElement.lambda_0_g$ (Runtime.java:166)

The 'null' argument work correctly

L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", null).addTo(map);

gwty-leaflet: 0.5 and 1.0-SNAPSHOT, GWT 2.8.0 and 2.8.1

How to pass another TileLayerOptions implementation to L.tileLayer ?

I'm wondering how to use a custom TileLayerOptions with :

public static native TileLayer tileLayer(String urlTemplate, 
TileLayerOptions options);

To call this method, you have to pass an instance of TileLayerOptions. But in the leaflet docs, there is no actual object that corresponds to TileLayerOptions, it's rather an object literal.

So how do you pass for example a TileLayerWMSOption to this method ? Or any other options map for another provider.

ps : I don't know why all the JsType constructors are mostly private, but because of that, we can't extend L to add other static method, or extend TileLayerOption.

Thanks

How to get absolute position from map latLng coordinate?

Hi, I was trying to get absolute or relative pixel position from latlng coordinate using map.latLngToContainerPoint() method. But it turns out this method returns position with respect to whole large map. How am I supposed to get screen position from this?

Thanks!

Native methods require a JavaScript implementation enclosed with /*-{ and }-*/

I wanted to use your library in my project where I use GWT and SmartGWT. But when I add map creation in my code I get compile errors as below. Could you tell what the problem is?

[INFO]    [ERROR] Errors in 'com/gwidgets/api/leaflet/L.java'
[INFO]       [ERROR] Line 76: Native methods require a JavaScript implementation enclosed with /*-{ and }-*/
[INFO]       [ERROR] Line 85: Native methods require a JavaScript implementation enclosed with /*-{ and }-*/
[.........]
[INFO]    [ERROR] Errors in 'com/gwidgets/api/leaflet/LatLng.java'
[INFO]       [ERROR] Line 65: Native methods require a JavaScript implementation enclosed with /*-{ and }-*/
[........]
etc.

createTile in GridLayer

Hi, I noticed in GridLayer, that createTile does not yet exist. Are there any updates on this? I am new to jsinterop, would this work?

@JsFunction
public interface FunctionCreateTile {
HTMLElement createTile(coords);
}

@JsMethod
public native L createTile(FunctionCreateTile fn);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.