Browsers let you ask the user their location, giving you their exact latitude and longitude. To get the lat/lon via TeaVM, use the following code:
HTMLBodyElement body = document.getBody();
final HTMLElement p = document.createElement("p");
body.appendChild(p);
if (Navigator.isGeolocationAvailable()) {
Navigator.getGeolocation().getCurrentPosition(new PositionHandler() {
@Override
public void handlePosition(Position position) {
final Coordinates coords = position.getCoords();
p.appendChild(document.createTextNode("Lat/Lon: " + coords.getLatitude() + "/" + coords.getLongitude() + " accuracy=" + coords.getAccuracy() + " heading=" + coords.getHeading()));
}
}, new PositionErrorHandler() {
@Override
public void handlePositionError(PositionError positionError) {
// Handle errors by looking at positionError.getCode()
}
});
} else {
p.appendChild(document.createTextNode("This browser doesn't support geolocation"));
}
Be sure to use a recent build of TeaVM from bintray that includes the geolocation API.
Next Steps
Once you have the user's location, what useful things can you do?
- Show their location on a map
- Tag photos or postings with a location
- Pair them up with other nearby users
Last modified on 27 Nov 2018 by AO
Copyright © 2024 Andrew Oliver