Google Maps Tutorial - Part 1
As promised part 1 of the Google Maps tutorial. See the original post for the plan for this series of posts.
We are going to build on the code in the original post.
In this part we are going to add a text box that allows the user to enter a street address (e.g. 123 Main street), and the map will center on that location.
We have already seen how to center the map using the "setCenter" method of the GMap2 object. Unfortunately "setCenter" does not work with a street address, you need to specify the full latitude and longitude coordinates. In order to do the conversion between street address and latitude/longitude, we use the GClientGeocoder object that is part of the Google Maps API.
First in the initialize function, which is called when the web page is loaded, we create a GClientGeocoder object.
-
function initialize() {
-
if (GBrowserIsCompatible()) {
-
map = new GMap2(
-
document.getElementById("map_canvas"));
-
var center = new GLatLng(37.4419, -122.1419);
-
map.setCenter(center, zoom);
-
-
map.addControl(new GSmallMapControl());
-
geocoder = new GClientGeocoder();
-
}
-
}
Note also that we added a small map control to the map. This will put a small control on the corner of the map which the user can use to pan and zoom the map.
We create a form so that when the user enters the street address and submits the form, the function findCenter is called and it is passed the argument that the user entered in the text box.
-
function findCenter(address) {
-
if (geocoder) {
-
geocoder.getLocations(address, findCenterCallback)
-
}
-
}
This function issues a query to Google with the street address as an argument. You also specify a callback function, "findCenterCallback", which is called by Google when it is done processing the getLocations request.
The findCenterCallback gets the return response from Google, and the rest of the processing can be done on the client side javascript code.
-
function findCenterCallback(response) {
-
if (!response || response.Status.code != 200) {
-
alert("address not found");
-
} else {
-
place = response.Placemark[0];
-
point = new GLatLng(place.Point.coordinates[1],
-
place.Point.coordinates[0]);
-
map.setCenter(point, zoom);
-
}
-
}
First the "response" variable is checked to make sure there are no errors.
Then the lattitude and longitude coordinates are extracted from the response, and a new GLatLng object is created. This GLatLng object (point) can then be used to set the map center using the "setCenter" method.
And that's it we are done! You can check out the full taxi application demo
Stay tuned for next time, when we will work on part 2 of the tutorial.
Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.



[...] First we start with the starting point google map implementation, from the last post. [...]