jQuery and Google Maps #2: AJAX Storing and Retrieving Points : jQuery, Google Maps

jQuery and Google Maps #2: AJAX Storing and Retrieving Points

Category: JavaScript & jQuery Tags: jQuery, Google Maps | Written on Apr 28, 2009

Note on April 30th: This article was updated do to feedback from Google Maps API team to use the Client Geocoder instead of encoding on the server.

Continuing the series on jQuery and Google Maps, I will teach you how to store and retrieve points with using AJAX and a server-side language. This tutorial will use PHP/MySQL on the server, but it is basic enough that re-writing in another language should not be difficult.

View Final Demo

Google maps add point with jQuery

First, let me share with you the design-pattern behind the tutorial. My design pattern has two steps. The first is to use a simple HTML form to create new locations by posting the data to the server via AJAX. The second step is to fetch those locations from the server also via AJAX. Sound simple? Well, then lets get started...

Note: This tutorial builds on the first tutorial's code, so all code I am showing you here will be added onto it.

Step #1: Create the, "Add Location" Form

To allow users to add locations to the map, let's create a basic form. This will include the parts of an address, as well as the name of the location.

HTML:
  1. <form id="add-point" action="map-service.php" method="POST">
  2.     <input type="hidden" name="action" value="savepoint" id="action">
  3.     <fieldset>
  4.         <legend>Add a Point to the Map</legend>
  5.         <div class="error" style="display:none;"></div>
  6.         <div class="input">
  7.             <label for="name">Location Name</label>
  8.             <input type="text" name="name" id="name" value="">
  9.         </div>
  10.         <div class="input">
  11.             <label for="address">Address</label>
  12.             <input type="text" name="address" id="address" value="">
  13.         </div>
  14.         <button type="submit">Add Point</button>
  15.     </fieldset>
  16. </form>

A couple things to note about the form:

  • The form's action is pointed to map-service.php, which is where we will process the form data.
  • A hidden input <input type="hidden" name="action" value="savepoint" id="action"> will be used on the server to flag that we want to save a point to the database. This is just a personal preference on how to do things, there are many other ways to flag the intended action.
  • An empty div with class error <div class="error" style="display:none;"></div> is placed in the form to be used in a later step to display errors.

Step #2: Add Styles to the Form

By adding a few CSS rules to our page, we will set our form next to the map and spruce up the form a bit.

Css:
  1. #add-point { float:left; }
  2. div.input { padding:3px 0; }
  3. label { display:block; font-size:80%; }
  4. input, select { width:150px; }
  5. button { float:right; }
  6. div.error { color:red; font-weight:bold; }

Step #3: Geoencode Address Before Submiting Data

3a) Override default form submit

At this point we'll override the form's default submit action by selecting the form $("#add-point"), then using jQuery's submit event method. This method accepts a function that will run on submit of the form.

JavaScript:
  1. $("#add-point").submit(function(){
  2.     geoEncode();
  3.     return false;
  4. });

3b) Add GeoCoder

Then, inside the submit we will post the form data with AJAX using jQuery's ajax post method.

JavaScript:
  1. var geo = new GClientGeocoder();
  2.                
  3. var reasons=[];
  4. reasons[G_GEO_SUCCESS]            = "Success";
  5. reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address";
  6. reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address.";
  7. reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address";
  8. reasons[G_GEO_BAD_KEY]            = "Bad API Key";
  9. reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries";
  10. reasons[G_GEO_SERVER_ERROR]       = "Server error";

3c) Get geocode from address

JavaScript:
  1. function geoEncode() {
  2.     var address = $("#add-point input[name=address]").val();
  3.     geo.getLocations(address, function (result){
  4.         if (result.Status.code == G_GEO_SUCCESS) {
  5.             geocode = result.Placemark[0].Point.coordinates;
  6.             savePoint(geocode);
  7.         } else {
  8.             var reason="Code "+result.Status.code;
  9.             if (reasons[result.Status.code]) {
  10.                 reason = reasons[result.Status.code]
  11.             }
  12.             $("#add-point .error").html(reason).fadeIn();
  13.             geocode = false;
  14.         }
  15.     });
  16. }

Step #4: Submit Data to Server

JavaScript:
  1. function savePoint(geocode) {
  2.     var data = $("#add-point :input").serializeArray();
  3.     data[data.length] = { name: "lng", value: geocode[0] };
  4.     data[data.length] = { name: "lat", value: geocode[1] };
  5.     $.post($("#add-point").attr('action'), data, function(json){
  6.         $("#add-point .error").fadeOut();
  7.         if (json.status == "fail") {
  8.             $("#add-point .error").html(json.message).fadeIn();
  9.         }
  10.         if (json.status == "success") {
  11.             $("#add-point :input[name!=action]").val("");
  12.             var location = json.data;
  13.             addLocation(location);
  14.             zoomToBounds();
  15.         }
  16.     }, "json");
  17. }

The $.post method accepts parameters.

  1. URL to post data to: $(this).attr('action') will get the action attribute from the form that was submitted in the previous step.
  2. Data in name, value pairs i.e. { name: "inputname", value: "inputvalue" } we will get all the inputs using the :input selector in jQuery, then use the serialize array function to turn those inputs into name, value pairs. Then add the two geocode name/value pairs to the data object.
  3. Function to run after AJAX response is received. This function has one parameter which contains the response of the AJAX request.
  4. Type of data to be returned (optional). In this case we will use JSON.

Step #5: Use PHP on the Server to Process the Form

Once the data is posted with jQuery, we can handle it on the server with PHP.

5a) Check the action and validate the name

Let's simply check if the action variable is posted as, "savepoint". Then validate that the name has the proper characters with a regular expression and also that it is not empty. If any data is invalid, let's call a fail method (defined in next sub-step) with the message we want to show to the user.

PHP:
  1. <?php
  2. if ($_POST['action'] == 'savepoint') {
  3.     $name = $_POST['name'];
  4.     if(preg_match('/[^\w\s]/i', $name)) {
  5.         fail('Invalid name provided.');
  6.     }
  7.     if(empty($name)) {
  8.         fail('Please enter a name.');
  9.     }
  10. }
  11. ?>

Save the file as map-service.php or whatever you named your form's action attribute.

5b) Output the error message as a JSON object

Our fail function will use PHP's die method to stop the script from executing and output an error message to the client. Since the front-end (jQuery) is expecting a JSON object, we want to make sure to always send back a JSON response. To output JSON with PHP, you simply pass an array into the json encode method (json_encode is PHP 5.2+ only, if you are using less than 5.2 then use the JSON PHP library).

PHP:
  1. function fail($message) {
  2.     die(json_encode(array('status' => 'fail', 'message' => $message)));
  3. }

For the JSON array we want to use the JSEND specification for sending back a response. Basically, you have a key/value pair of status equals success or fail. That way the response can easily be checked on the front-end. I'm deviating from the JSEND spec a little bit by only sending a string back instead of a key/value pair of messages.

Using Firebug and Firefox, we can inspect the Ajax requests easily within the browser.

You can see here I submitted the form without entering a name and it sent me back an error message in the form of JSON.

Step #6: Display the Error Messages with jQuery

Hopping back to the jQuery code, we will write the error handling.

Inside the post code, we will first use the hide method to hide the error div in case it is already displaying. Then check if json.status is showing, "fail". If it is, we'll place the json.message inside the error div with jQuery's html attribute method and then fade it in with the fade in method.

JavaScript:
  1. $("#add-point .error").hide();
  2. if (json.status == "fail") {
  3.     $("#add-point .error").html(json.message).fadeIn();
  4. }

Step #7: Create a Database and Store the Locations

Using SQL, create a database table named locations which has a "name", "latitude", "longitude" and an "id" in it. If you need help with this, you will have to consult w3schools php and mysql for more help.

7a) Create the table with SQL

Mysql:
  1. CREATE TABLE `locations` (
  2.   `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  3.   `name` VARCHAR(100) DEFAULT NULL,
  4.   `lat` FLOAT(15,11) DEFAULT NULL,
  5.   `lng` FLOAT(15,11) DEFAULT NULL,
  6.   PRIMARY KEY  (`id`)
  7. )

7b) Insert name and location into the database with PHP and MySQL

We will use PHP and MySQL to insert the new location into the database. Directly after, we will either flag a success or fail message to the user.

PHP:
  1. $query = "INSERT INTO locations SET name='$_POST[name]', lat='$lat', lng='$lng'";
  2. $result = map_query($query);
  3.  
  4. if ($result) {
  5.     success(array('lat' => $_POST['lat'], 'lng' => $_POST['lng'], 'name' => $name));
  6. } else {
  7.     fail('Failed to add point.');
  8. }

If you noticed, I created a custom function called map_query to abstract out the database stuff. Here is the function definition. Make sure to update the, "MYSQL" stuff with your credentials.

PHP:
  1. function map_query($query) {
  2.     mysql_connect('MYSQL_HOST', 'MYSQL_USER', 'MYSQL_PASSWORD')
  3.         OR die(fail('Could not connect to database.'));
  4.     mysql_select_db ('MYSQL_DATABASE');
  5.     return mysql_query($query);
  6. }

I also created a similar method to "fail" called "success" which looks like:

PHP:
  1. function success($data) {
  2.     die(json_encode(array('status' => 'success', 'data' => $data)));
  3. }

An example of a succesful response in firebug:

Step #8: Map the New Point

Going back to the jQuery code, we can now add the success response handling. The response is a JSON object with "lat", "lng" and "name" properties. I'll give you the code inside the success handling, then later show you what each custom function is doing.

JavaScript:
  1. if (json.status == "success") {
  2.     $("#add-point :input[name!=action]").val("");
  3.     var location = json.data;
  4.     addLocation(location);
  5.     zoomToBounds();
  6. }

After a location is successfully added to the database, we want to clear the form to prevent duplicate entry. Do this by selecting the inputs with the :input selector. Then we need to filter out the  action input, do this by using the attribute not equal selector [name!=action].

My addLocation(location) function is simply our code from the last tutorial placed into a function to be reusable later.

JavaScript:
  1. function addLocation(location) {
  2.     var point = new GLatLng(location.lat, location.lng);       
  3.     var marker = new GMarker(point);
  4.     map.addOverlay(marker);
  5.     bounds.extend(marker.getPoint());
  6.    
  7.     $("<li />")
  8.         .html(location.name)
  9.         .click(function(){
  10.             showMessage(marker, location.name);
  11.         })
  12.         .appendTo("#list");
  13.    
  14.     GEvent.addListener(marker, "click", function(){
  15.         showMessage(this);
  16.     });
  17. }

It has a few things you might want to note:

  • using location.name, location.lat and location.lng means that we will be passing in a location object with those properties to the function.
  • Ignore bounds.extend(marker.getPoint()); and zoomToBounds for now or skip to #13 quickly to find out what they do.

Step #9: Load and Display the Locations from in the Database

When the page initially loads, we want to load all of our stored points. The simplest way to do this (in my opinion) is to do a GET request to fetch a JSON object from the server after the page loads.

To make a, "GET" request to the server, we can use jQuery's getJson method. We will send the server a, "get" variable called action with value, "listpoints".

JavaScript:
  1. $.getJSON("php/map-service.php?action=listpoints", function(json) {
  2.     // do stuff in step #11
  3. });

Step #10: Get the Locations from the Database

Simply check the, "GET" action in the PHP and run this code to fetch the locations records. Pretty straight-forward code here. We are creating an array of points and then sending them back to the client as JSON.

PHP:
  1. if ($_GET['action'] == 'listpoints') {
  2.     $query = "SELECT * FROM locations";
  3.     $result = map_query($query);
  4.     $points = array();
  5.     while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
  6.         array_push($points, array('name' => $row['name'], 'lat' => $row['lat'], 'lng' => $row['lng']));
  7.     }
  8.     echo json_encode(array("Locations" => $points));
  9.     exit;
  10. }

Step #11: Display the Locations

Iterate through the JSON object that contains the locations inside the getJson response function.

Comments

#1. fugazi http://itmtelecomunicaciones.blogspot.com on Apr 28, 2009
thank you so much!! :)
#2. JDStraughan http://tutlist.com on May 05, 2009
This is a great tutorial. Thanks. Added to tutlist.com
#3. Mohammed on May 21, 2009
Great
I have a suggestion. Can you explain how to allow the user to click the point that he/she wants to save on the map.
#4. Nick Palmigiano http://www.nickpalmigiano.com on May 22, 2009
Excellent post! I've been looking for something like this for awhile since I've been unable to make it myself. I am curious, like Mohammed, what if the map is being used for an area like a bike or canoe trail? I realize that its just geocoding that one point and having those variables stored away like the main bulk of this tutorial, but finding that one point based on a click event seems elusive to me.

Good work though!
#5. joyce on May 25, 2009
<html>
<head></head>
<body>
thank for sharing its work well.I have try to modify but i got a question how if i wan to change the code from passing form input value to javascript variable. Is it possible? i have try this
var finalpoint="1.234,23.552";

var data = $("#add-point").serializeArray();

data[data.length]={name:"sam", value:finalpoint};

alert (data[0]);

$.post($("#add-point").attr('action2'), data, function(json){

</body>
#6. Mini0n on Jun 22, 2009
Hi there! Nice tutorials you have here!
Will you make some more on this subject, jQuery+Google Maps? It was very nice.

Thanks for your explanations. =)
#7. Tim Nott http://captimes.com on Jun 24, 2009
Absolutely fabulous tutorial - thanks
#8. Tim Nott http://captimes.com on Jun 24, 2009
One issue - IE does not seem to understand that the li:hover applies to the list. Is this perhaps because they are added after the fact?
#9. Mitch on Jun 26, 2009
Great tutorial, thank you Marc!
#10. Henry on Jun 30, 2009
is it possible to do this with a google map i already saved (its about 150 points of data that i dont wanna type in again.)
#11. John on Jul 10, 2009
Tim, ie6 doesn't understand :hover on non-a elements
#12. Zed on Jul 10, 2009
Thanks for share this cOol Tut.
#13. Wolfgang on Aug 25, 2009
Thank you for this great tutorial !!!!
I learned so much and wrote a Joomla sample.
Keep on writing !
#14. chandler http://domain.com on Sep 05, 2009
Really thanks,I learned a lot
#15. mark http://www.soddengecko.com on Sep 21, 2009
I am having some trouble with this. Basically when I add a new point by address or lat/lng it shows up on the map in the correct place but updates the database with 0.00000000000 for both lat and long.

if i then refresh the page the pointer moves to 0.00000000000,0.00000000000 on the map which is obviously no good. I have tested this with IE, Chrome and Firefox and all do the same thing

any ideas as to why this is happening?

Cheers
#16. Marc Grabanski http://marcgrabanski.com on Sep 21, 2009
1) Check what coordinates are being sent to the backend by inspecting the POST request with Firebug.
2) Verify the names of the POST variables are retrieved on the backend by echoing(logging) the variables.
3) Verify the SQL is sending out the correct column names into the database, try echoing(logging) the entire SQL statement.
#17. mark http://www.soddengecko.com on Sep 21, 2009
Thank you Marc

In the map-services.php file the lat and lng variables were not being collected from the post. I added the $_POST[] to these variables and it worked like a charm.

Do you plan to update this with extra function like draggable pointers that update once dropped and a close button inside the message div?

Thank you for a great piece of code, has served my purposes well
#18. Ronald Nunez http://ronaldnunez.com on Oct 09, 2009
Great tutorial I just need like this one for one of my project thanks for sharing
#19. Dexter on Oct 27, 2009
Great tutorial! For further development, do you plan to add on-click adding markers and dragable pointers?
#20. Daan on Nov 11, 2009
Thanks! This was exaclty what I needed. I've modified it to include urls so one can click on the messages and go to a website. Keep going with this stuff!
#21. Emanuele on Nov 12, 2009
Hi, I've the latest stable build of jQuery and I'm using you script. The problem is this:

function showMessage(marker, text){
var markerOffset = map2.fromLatLngToDivPixel(marker.getPoint());
$("#message").hide().fadeIn()
.css({ top:markerOffset.y, left:markerOffset.x })
.html(text);
}


.css({ top:markerOffset.y, left:markerOffset.x }) doesn't work like you want, in my page, the #message doesn't "follow" my point in the map if I go down and up :(
#22. Serial on Nov 29, 2009
Hi,

I'm having a little problem getting this to work. It won't store the points in my database. It doesn't seem to connect to the php file at all. Ive checked the response with firebug and it does make the point after pressing the button. But after that nothing. I used the example files and only edited the database connect stuff and the link to the php file. I'm sure the error is not in the php file.

Any idea what it could be ? I'm testing locally.
#23. Serial on Nov 29, 2009
Just to clarify.. I'm getting nothing when checking console with firebug. Nothing happens when I press add point. But when I check the JS at net I do get a correct output.
#24. Roach http://urbandev.net on Dec 19, 2009
in: Step #7: Create a Database and Store the Locations

Using SQL, create a database table named locations which has a "name", "latitude", "longitude" and an "id" in it. If you need help with this, you will have

This is incorrect as map-service.php in the demo is referencing "name", "lat", "lng" and "ip"
#25. Anand http://www.anandsueman.com on Jan 14, 2010
First off wicked tutorial!!!! But ran into some trouble setting up my own get data and displaying it ;
I have set up my own way of getting the location( this by clicking on the map and it get's the code(i have tested it and it returns the data ineed from database).... I am trying to use the json method to display the saved data.. so i modified the index html matching the fields of my database table...
But i get nothing

The field i wanna call up are the following "title", "lat" and "lng"
i haven't stored the ip because i don't need it...

i don't need the form to enter the data because i have separated them ( so input and display seperate )

what i am goin to do is to search in the database on the display page example: mapengo.anandsueman.com so you get an idea

what am i doing wrong here... please help ...

this is my out from database with json ;
Array ( ) {"Locations":[{"title":"Megastores","lat":"52.065605","lng":"4.317820"},{"title":"some title hogeschool","lat":"52.067062","lng":"4.324284"},{"title":"Bart Osso","lat":"52.068172","lng":"4.328916"}]}
#26. Anand http://www.anandsueman.com on Jan 20, 2010
Can anyone point me to the right direction how to integrate this a mysql database and php ?

Please help ..
#27. Feelicjan on Feb 07, 2010
Great tutorial! BTW, can anyone tell me how to change the script so that points are still there when i reload the site? At this point, reloading the website means that all the points disappear even though they are in the database. Can anyone give me a hint? Regards.
#28. timani http://timani.net 6 days, 2 hours ago
Nice plugin detailed writeup to get going on! retweeting!
#29. ahtsham http://ahtsham.com 4 days, 1 hour ago
thanks for good code.. But i have one question can someone tell me how i remove the previous mark on Google map Because when i change the address i want to show the current mark not old one. please help me soon
thanks advance
#30. Jason http://macko.me 3 days, 4 hours ago
Awesome idea and even better with the tutorials 8]

Just one bug that i found - Clicking on the location gives the text, on zooming in/out the text displayed stays there but it is in the incorrect location now. This could be fixed by detecting double click and removing the text.

Just an idea to look into 8]
#31. Marc Grabanski http://marcgrabanski.com 3 days, 3 hours ago
Hey Jason, thanks for your idea. I was planning to do that within future parts of the series, but unfortunately I have not gotten past part 2. ;)
#32. Jason http://macko.me 3 days, 1 hour ago
Hi Marc,

Will be looking forward to any future developments 8] In the meantime, time to start learning ajax for me 8]

Not sure if you did this on purpose or this is how it works with different versions of php/MySQL, in the tutorial you have above in Step #7b you have:

$query = "INSERT INTO locations SET name='$_POST[name]', lat='$lat', lng='$lng'";

However, in the zip downloadable file the supplied the code for that line is

$query = "INSERT INTO locations SET name='$_POST[name]', lat='$_POST[lat]', lng='$_POST[lng]', ip='$ip'";

I kept getting the Failed to add point. message until i changed this around to what you had in the tutorial.

Thanks again. 8]

Leave a Comment

Other Reading - Categories