Mapping an address in a JavaFX application is extremely easy with the Geocoding API that was recently introduced in GMapsFX. In this blog post I’ll walk through an example of setting up an application with a map and a text field. The map will recenter itself at whatever address or place the user types in the text field.
Starting off with the FXML file, we have an AnchorPane which contains the GoogleMapView and a TextField. The AnchorPane has a controller assigned to it named FXMLController, and both components have an FX ID associated with them so they will be accessible from the FXMLController class. Also, the TextField has an action, “addressTextFieldAction” associated with it, so this method will be called when the user hits the ‘Enter’ key in the TextField.
The result should look as follows:
Next, I’ve cut up the relevant parts of the FXMLController class. The MapComponentInitializedListener interface needs to be implemented by the controller since the underlying GoogleMap doesn’t get initialized immediately. The GoogleMapView and TextField components from the FXML file are defined below and annotated with @FXML.
There is also a reference to the GeocodingService as well as a StringProperty to represent the address the user enters.
After the controller is created its initialize method is called which will set the MapView’s initialization listener to the FXMLController as well as bind the address property to the address TextField’s text property.
Once the map has been initialized, the GeocodingService can be instantiated as well as a MapOptions object to set various attributes about the map. Once the options are configured, a GoogleMap object can be instantiated from the map view.
Finally, the action method defined in the FXML file when the user hits ‘Enter’ in the TextField is below. The method will call the geocode() method on the GeocodeService class, passing in the value of the Address property as well as a callback method.
The callback will check the status of the results, and based on the outcome, will recenter the map at the latitude/longitude the user had entered.
Below is an example when the user enters New York City as the address.
That’s it! For completeness I’ll include the full source code of the example below.