Google Maps API Tutorial

© 2007, 2008, 2009 Mike Williams

 
Translate this page:

 

Storing User Input

A common requirement is to allow users to input data onto your map which will then become available to other users.

You can't write files directly from Javascript, so you have to send the data back to a server script and arrange for the server to store the data in a database on your server.

Javascript can send the data to the server using GDownloadUrl.

If there are always going to be less than 512 bytes to send, then you can use the normal format of GDownloadUrl, which sends a GET request to the server:

  GDownloadUrl(
   "myserver.php?lat=1.12&lng=-23.45&details=This is my house",
   function(doc){}
  );
If there may be more that 512 bytes of data, then you'll need to use the undocumented POST form of GDownloadUrl
  GDownloadUrl(
   "myserver.php",
   function(doc){},
   "lat=1.12&lng=-23.45&details=This is my house"
  );
Here's a simple example

Some considerations

Javascript code launched from HTML (e.g. from the SUBMIT button of a form) executes in global context, so it can only access local variables. In the example, I store a global reference to the last input marker that had its info window opened, "lastmarker". Since the API only supports one info window being open at once, this will be the marker associated with the SUBMIT button click.

I've made the input markers draggable so that the user can adjust the position.

I've used a different icon for the input markers and the normal markers. I reckon it gets confusing otherwise.

I've set the {draggableCursor} to "default". This makes it easier for the user to position the click accurately.

Don't allow untrusted users to enter HTML content into your info windows.
In this example, I've used the text node version of marker.openInfoWindow() rather than marker.openInfoWindowHtml(), so thay if anyone attempts to do something nasty, like embed a malware file, all that happens is that <embed src="http://malware.file"> gets displayed in the text.
You might want to do something more sophisticated, like removing anything between < and >.

Googlepages doesn't support server scripts, so my example doesn't actually send the data to a server. In your real page you'd remove the "//" from the beginning of the GDownloadUrl() command.

This is just a simple example. In a real page you might want to allow users to edit or delete markers that they had previously created. You might even want to allow them to perform a limited amount of markup in the text. That's not going to be particularly easy.

Back to Mike's Homepage
Up to the start of this tutorial