Yes you can create your own javascript engine in Java. This is a cool feature I never knew existed. I don’t know how long it’s been around, I’m guessing Java 6.
Translating a geographical location such as “London, UK” into a lat/long coordinate (lat: 51.5085150, long: -0.1254870) is called geocoding. This coordinate can then be used to display the location on google map.
Try putting a location in the box below and hit go:
Register for Google Map API Key
In order to implement the above widget first obtain an API key from Google:
Go to
Select Services on the left menu, ensure Geocoding API, Google Maps Embed API and Google Maps JavaScript API v3 are turned on
Go to API Access, select Create new Browser key
The list of accepted HTTP referers will be asked, if you’re testing on local machine this would probably be localhost/*, otherwise you need to put your website domain name here. Hit Create once you’re done
Take a note of your API key, this will be used in the later part of this tutorial
The HTML Code
This widget only contains 3 elements:
A text input box to provide the geographical location
A button to submit the address and show it on the map
A div container for the map
Enter location (eg: London, UK):
Javascript
2 javascript libraries are used: jQuery and Google Map JS. The key parameter on the Google Map JS URL should be the key created above.
Firstly let’s initialize the div container so it doesn’t come up with blank map, here I set it into coordinate of San Francisco, CA:
$(document).ready(function() {
var map = new google.maps.Map($('#map')[0], {
center: new google.maps.LatLng(37.7749295, -122.4194155),
zoom: 8
});
...
}
And create a click handler for the ‘Go’ button which sends ajax post into Google Map JS API. The API will return a JSON response with the location if successful.
$(document).ready(function() {
...
$('#go').click(function(e) {
e.preventDefault();
var loc = $('#loc').val();
$.ajax({
url: '//maps.googleapis.com/maps/api/geocode/json?sensor=false&address='+loc
}).done(function(data) {
if(data.status != "OK") {
alert("Unable to find location");
return;
}
var loc_result = data.results[0].geometry.location;
map.setCenter(new google.maps.LatLng(loc_result.lat, loc_result.lng));
});
});
});
An excellent walkthrough on how to do a content box that autoloads when scrolled to the end of the page: http://webdeveloperplus.com/jquery/create-a-dynamic-scrolling-content-box-using-ajax/
Gerry's software development journey of trial, errors and re-trials