This app looks up the street address and zipcode of the
Woolworth Building,
given its latitude and longitude:
Latitude 40.712222° North
Longitude 74.008056° West
See the JavaScript
Geocoding
Service.
Conversion from latitude and longitude to street address is called
reverse geocoding.
The JavaScript function
onFound
in
page.html
is called when the
Geocoder
object finds the street address and zipcode
of the given latitude and longitude.
I named it
onFound
because it’s like an Android listener.
The
results
argument of
onFound
is an array of
GeocoderResult
objects.
We examine only the first element of this array.
The element contains an array of
GeocoderAddressComponent
s,
each of which contains a
type
and
long_name
.
MainActivity.java
activity_main.xml
contains a
WebView
.
page.html
in the
assets
folder.
AndroidManifest.xml
:
a
WebView
requires
uses-permission
INTERNET
.
The
page.html
to which the URL refers must be in the assets folder in the Android Studio
project
view.
Select the app folder at the top of the
project
view.
Pull down
File → New… → Folder → Assets Folder
Finish
Remember to add the
uses-permission
to
AndroidManifest.xml
.
Select the
assets
folder in the Android Studio
project
view.
File →
New… →
File
Enter a new filename: page.html
OK
MainActivity
.
class DualCitizen { //This method, although written in Java, can be called in a JavaScript statement. @JavascriptInterface public void setZipcode(String z) { int zipcode = Integer.parseInt(z); Toast toast = Toast.makeText(MainActivity.this, "Zipcode is " + zipcode, Toast.LENGTH_LONG); toast.show(); } }
loadURL
at the end of
onCreate
.
//Create a new Java object, and specify the name it will have when it //appears in the JavaScript program. webView.addJavascriptInterface(new DualCitizen(), "dualCitizen");
onFound
in
page.html
,
insert the following statements immediately before the
break
.
var zipcode = results[0].address_components[i].long_name; dualCitizen.setZipcode(zipcode);
Toast
displaying the zipcode of the location.