Creating an Interactive Travel Map using the Google Maps API

This is my third tutorial on the Google Maps API v3. I’m going to show you how to use some other google maps features by building an interactive travel map. Everyone will be able to add new locations on the map and view the locations added by others. We will also be using MySQL databases to store the values of different locations so let’s get started.

What google maps features you’ll learn?

  • Adding a map to your site
  • Adding controls for the map and settings the options for the controls
  • Responding to events
  • Adding markers, settings options for markers and dynamically changing marker settings
  • Geocoding a location
  • Creating tabbed infowindows (using jquery, jquery ui and some sample code from google code)


The application is built using html, php and javascript and also saves the locations in a mysql database. It would be best if you had some basic knowledge of these.

What are we going to build?

We’re going to build an interactive travel map. Everyone will be able to see the locations on the map and also add new ones easily. We’ll save some info about each location (coordinates, address, a description, a photo and data about the person who added the location). Users will be able to add locations by clicking on the map to find out the coordinates and address and by filling in the rest of the info. The users will also be able to view all the locations from the database. For viewing them easier, we’ll add a location list the user can browse and we will highlight a location on the map when the user goes with the mouse pointer over the location name.

You can view the app here! And also download the source code from here.

Creating the database table

First we have to create a table in our database to save the data about the locations on the map. We’ll save the following data about each location:

  • A name
  • A description
  • A photo
  • Coordinates: latitude and longitude
  • Address
  • Info about the user who added the location: name and location

Here’s how the code for creating the table looks like:

`name` text NOT NULL,
`description` text NOT NULL,
`photo` text NOT NULL,
`latitude` double NOT NULL,
`longitude` double NOT NULL,
`address` text NOT NULL,
`user_name` text NOT NULL,
`user_location` text NOT NULL,
PRIMARY KEY (`id`));

Creating the layout for our app

We’ll use a simple layout. We’ll show a title and some info about our app at the top of the page. Below that we’ll add three columns, one for adding locations (with a form for adding new locations), one for the map (a div called ‘map_canvas’) and one for the locations list.

Since the code is pretty long I’ve decided not to post it here, but you can see it in the source code of the app.

Connecting to the database and getting the info about the locations

To get the data from the database we’ll first have to connect to it. We’ll create a small php script for this and save it in the ‘connect.php’ file. The script looks like this:

$username = "WRITE_USERNAME_HERE";
$password = "WRITE_PASSWORD_HERE";
$connId = mysql_connect($server,$username,$password) or die("Cannot connect to server");
$selectDb = mysql_select_db($database,$connId) or die("Cannot connect to database");

Don’t forget to fill in your data!

We’ll include this script in our main file and the database connection is done! We’ll add the following lines at the beginning of our main file:

include "connect.php";

Now we need to find out the number of locations and the information about all the locations in the database.

Here’s how:

$locations = mysql_query("select * from locations");
$nr_locations = mysql_num_rows($locations);

We have done a simple query to the database and retrieved the info about the locations in the $locations variable. We have also found out the total number of saved locations. We will print this in the text we’ll show on top of our page:

Click on the map to add a new location! Total locations added: <?php echo $nr_locations;?>

We also have to print the location list, like this:

// find locations from db
// save data for locations
$lats = "";          // string with latitude values
$lngs = "";          // string with longitude values
$addresses = "";     // string with address values
$names = "";         // string with names
$descrs = "";        // string with descriptions
$photos = "";        // string with photo names
$user_names = "";    // string with user names
$user_locs = "";     // string with user locations
// take the locations from the db one by one
while ($locat = mysql_fetch_array($locations))
  // add location data to info strings
  $lats .= $locat['latitude'].";;";
  $lngs .= $locat['longitude'].";;";
  $addresses .= $locat['address'].";;";
  $names .= $locat['name'].";;";
  $descrs .= $locat['description'].";;";
  $photos .= $locat['photo'].";;";
  $user_names .= $locat['user_name'].";;";
  $user_locs .= $locat['user_location'].";;";
  // show the location name in the right of the map with link that calls the highlightMarker function
<a onmouseover="highlightMarker(<?php echo $i;?>)"><?php echo $locat['name'];?></a> <br/>
// hidden inputs for saving the info for all the locations in the db
<input type="hidden" value="<?php echo $lats;?>" id="lats" name="lats"/>
<input type="hidden" value="<?php echo $lngs;?>" id="lngs" name="lngs"/>
<input type="hidden" value="<?php echo $addresses;?>" id="addresses" name="addresses"/>
<input type="hidden" value="<?php echo $names;?>" id="names" name="names"/>
<input type="hidden" value="<?php echo $descrs;?>" id="descrs" name="descrs"/>
<input type="hidden" value="<?php echo $photos;?>" id="photos" name="photos"/>
<input type="hidden" value="<?php echo $user_names;?>" id="user_names" name="user_names"/>
<input type="hidden" value="<?php echo $user_locs;?>" id="user_locs" name="user_locs"/>

We have shown the location names as links. When the user goes with the mouse over the links, the highlightMarker JavaScript function is called. We’ll take a look at it a bit later.

We have also saved the information about the locations in hidden input fields. We will use the info from the hidden fields to show the locations on the map.

Showing the map

To add the map we will first have to include the google maps api, like so:

<script src=""></script>

Now, we’ll define a javascript function called initialize to show the map in the div created for it. We will call this function after the page is loaded.

Here’s how to call the function when the page loads:

<body onload="initialize();">

And here’s the function code:

var geocoder;
var map;
// initializing the map
function initialize()
  // define map center
  var latlng = new google.maps.LatLng(57.279043,29.355469);
  // define map options
  var myOptions =
    zoom: 3,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.HYBRID,
    scaleControl: true,
    navigationControl: true,
    navigationControlOptions: {
      style: google.maps.NavigationControlStyle.SMALL
    mapTypeControl: true,
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
  // initialize map
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  // add event listener for when a user clicks on the map
  google.maps.event.addListener(map, 'click', function(event) {

To create a map, we first have to define the options for showing the map. We have set the zoom level, the center of the map. Next, we have set the controls to show on the map: scale control, navigation and map type and we have defined some options for it. We have chosen to show a small navigation control and to show the map type control as a drop down menu. You can view all the options available for controls in the API reference.

Then, we initialize the map object and add an event for when the user clicks on the map. When this event is fired, the findAddress function will be called. The function takes as an argument the coordinates of the point where the user clicked on the map.

// finds the address for the given location
function findAddress(loc)
  geocoder = new google.maps.Geocoder();
  if (geocoder)
  geocoder.geocode({'latLng': loc}, function(results, status)
    if (status == google.maps.GeocoderStatus.OK)
      if (results[0])
        address = results[0].formatted_address;
        // fill in the results in the form
        document.getElementById('lat').value =;
        document.getElementById('long').value = loc.lng();
        document.getElementById('address').value = address;
    alert("Geocoder failed due to: " + status);

This function uses the geocoding service from google maps to find the address corresponding to the coordinates where the user clicked on the map. When the function get the results from google, it shows the results in our form:

// fill in the results in the form
document.getElementById('lat').value =;
document.getElementById('long').value = loc.lng();
document.getElementById('address').value = address;

The user will just have to fill in the rest of the data to add a new location. I’ve not included here the php code to add the location to the database. You can see that in the source code!

Showing the markers

We will also have to show the locations on the map when it loads. We will call one more function when the page loads:

<body onload="initialize(); addMarkers()">

Let’s see how the function looks like:

// initialize the array of markers
var markers = new Array();
// the function that adds the markers to the map
function addMarkers()
  // get the values for the markers from the hidden elements in the form
  var lats = document.getElementById('lats').value;
  var lngs = document.getElementById('lngs').value;
  var addresses = document.getElementById('addresses').value;
  var names = document.getElementById('names').value;
  var descrs = document.getElementById('descrs').value;
  var photos = document.getElementById('photos').value;
  var user_names = document.getElementById('user_names').value;
  var user_locs = document.getElementById('user_locs').value;
  var las = lats.split(";;")
  var lgs = lngs.split(";;")
  var ads = addresses.split(";;")
  var nms = names.split(";;")
  var dss = descrs.split(";;")
  var phs = photos.split(";;")
  var usrn = user_names.split(";;")
  var usrl = user_locs.split(";;")
  // for every location, create a new marker and infowindow for it
  for (i=0; i<las.length; i++)
  if (las[i] != "")
    // add marker
    var loc = new google.maps.LatLng(las[i],lgs[i]);
    var marker = new google.maps.Marker({
      position: loc,
      title: nms[i]
    markers[i] = marker;
    var contentString = [
      '<li><a href="#tab-1"><span>photo</span></a></li>',
      '<li><a href="#tab-2"><span>description</span></a></li>',
      '<li><a href="#tab-3"><span>location</span></a></li>',
      '<p><img src="./photos/'+phs[i]+'"/></p>'+
      '<p>Added by: '+usrn[i]+' from '+usrl[i]+'</p>'+
      '<p>Address: '+ads[i]+'</p>'+
      '<p>Location: '+loc+'</p>'+
    var infowindow = new google.maps.InfoWindow;
    bindInfoWindow(marker,, infowindow, contentString);
// make conection between infowindow and marker (the infowindow shows up when the user goes with the mouse over the marker)
function bindInfoWindow(marker, map, infoWindow, contentString)
  google.maps.event.addListener(marker, 'mouseover', function() {
    infoWindow.setContent(contentString);, marker);

We will also save the markers in an array.

We will take the information about the locations from the hidden input fields we have created earlier. We will create a new marker for each of the locations. The title of the marker will be the location name. We’ll also create some infowindows to show when the user goes with the mouse over the markers. As you can see, we have used another function to bind each marker to its infowindow. We’ve also centered the map on the marker when the user goes with the mouse over it.

To show the information about the markers in the infowindow nicely, I have decided to use some sample code I found here. It uses jquery and jqueryui. We will also have to include these for the script to work:

<script src="jquery-1.4.2.min.js"></script>
<script src="jquery-ui-1.8rc3.custom.min.js"></script>
<link href="jquery-ui-1.8rc3.custom.css" rel="stylesheet" />

And we’re almost done!

All there’s left to do now is the highlightMarker function, the one called when the users goes with the mouse pointer over a location name in the location list. Let’s take a look at the function:

// highlighting a marker
// make the marker show on top of the others
// change the selected markers icon
function highlightMarker(index)
  // change zindex and icon
  for (i=0; i<markers.length; i++)
    if (i == index)

The function takes as an argument the index of the marker in the markers array we have created.  The highlightMarker function will make the selected marker show up on top of the other markers and change its icon. To make the marker on top of the others, we have to change the zIndex value of the marker.  The marker with the biggest value will show on top. We have set the selected markers value to 10 and the values of the rest of them to 2 (using the setZIndex function). We have also changed the icon of the marker with the setIcon function.

You might have noticed I also added a small javascript function to check if the user filled in all the information from the add form. The function is called when the form is submitted. It just checks the values filled in the form and if one of them is missing, it will show and error message and prevent the form from submitting.

And that’s it! We now have an interactive travel map!

Irina Borozan

Irina is a software developer from Bucharest, Romania. She enjoys working on various programming projects. She likes spending her spare time reading, hiking, travelling, skating or playing tennis. She also blogs a bit. You can find her online in her home on the internet and on twitter.

15 Smart Tools To Help You Build Your Freelance Business

Discover the awesome tools we use in making our clients comfortable and happy in learning new things every day.

Download Now


  1. Buzz says

    Hi Irina,
    Your tutorial helped me a lot! Thanx for this!
    I slightly modified your code to let the user choose between two icons for the marker via an select field in the form. It is saved to database as “green” and “blue”. I proceeded with the the variable all the same as with e.g. “user_name”. And all the variables works fine:

    var zeigers = document.getElementById(‘zeigers’).value;

    var zgrs = zeigers.split(“;;”)

    var loc = new google.maps.LatLng(las[i],lgs[i]);
    var marker = new google.maps.Marker({
    position: loc,
    title: nms[i],
    icon: ‘./images/’+zgrs[i]+’.png’

    But when it comes to the highlightMarker function, only the first Marker-Icon changes on Mouseover. Then nothing more happens.

    function highlightMarker(index)
    // change zindex and icon
    for (i=0; i<markers.length; i++)
    if (i == index)

    I know there are many other tutorials, and code snippets to get a marker-Icon changed on mouseover in a sidebar. But I want to know how I can do this with your code?
    What do I have to adjust? Where is the mistake?
    Would you be so kind and give me assistance?


  2. Delger says

    Hello guys. this nice example works good direct page but it does not work including any php web page. please tell me how to work in php web page by including.

  3. Tony says

    Insert the echo line, after line 306, to prevent double writings in the db when refreshing the page!

    // update photo name
    $result = mysql_query("update locations set `photo`='".$id."_photo.jpg' where id=".$id);
    echo "";

  4. MatBoy says


    This script is great, thanks!

    Is there a way to add lines between the ID’s that belong to the same username ?

    I also wondered if it’s possbible to show a marker at the moment you clicked on the map to show your new marker, maybe in a different color or so.

    • says


      Yes you could find a way to show which markers were added by the same user. You would have to do a check in your code and show the user names a bit differently for each user.

      Yes, showing a different colored marker is possible too :)

  5. morty says

    Irina thanks for the code! it is looking very promising.

    just having a small problem with the info windows, though.
    clicking the next marker dos not close the previous one.
    I have tried every solution i could find on how to only have one open at the time, but no go.
    it is not this complicated but nothing seems to work.

    any help would be amazing, cheers.

    • Irina says


      You would have to save in a variable the last opened window and close that before opening a new one. Let me know if you have any problems.

  6. Bob says

    I have a quick question. If you wanted to sort by names, would you use nms (the variable name) like
    for (var i=0; i<markers.length; i++) {
    if (nms[i] == names) {

    How would you filter a specific group of names?

    • says


      You would have to sort all the arrays that hold the data by the values in the nms array (the one with names) :)

  7. Kate says

    Hi! I really liked your code, il was great :)
    I was wondering, what part in the code is showing the adresses in the map?

    • says

      The addresses are obtained by making a request to a google service, based on the coordinates of the location.

  8. Alaa says


    i really like it

    i wanna ask u if there is a way to search for any location saved

    thanx :)

    • says

      Yes, you can add that to your map. You’ll just have to look through the entries in the database.

  9. Martin says

    hey irina,

    i was looking for tabed infowindow and finished at your tuturial – my tiny problem is, that the css is just working when i open the info window at the second time & then for the whole time, if i am reloading the brower i have to click on the marker and close it again…strange…any idea ?

    thx in advance

    • says

      Yes, I noticed too that the sample code I used has a small issue. I haven’t managed to fix it.

  10. Welou says

    I think i’ll have to predetermine the number of points(lat,long) the tours will contain or i can store the tours in text format in the database(like: (lat1,long1),(lat2,long2)…..). The user can just click around and the geocoder can pick up the points…
    But for displaying….i can fetch the points from the database,but how to i add the lines to connect the points?

  11. says

    The data is stored in a databased. I have showed how :)

    The marker first shows up when you click on the map and then the location data is stored in the database.

  12. says

    Hi, I’m glad you liked it!

    Yes, you can also store the tours in the database. You would have to decide exactly what to store about a tour and how to mark the tour on the map.

    • Jade says

      Hi Irina,
      I tried your codes..and they were working just fine..but now the tabs in the infowindows are nno longer showing.
      They are in bullet form…how can this be? was working just fine a few weeks ago…:(

  13. Welou says

    Hi Irina:)
    This tutorial has helped me so so much!…i just love the way you explain it all..this is so clear and its not difficult to understand at all..
    I was wondering if its possible to store tours as well in a database..???

    Hope to hear from you soon:)

  14. Russell says

    I couldn’t think how the form has submitted to database after a checking . Does the application store in database or array? And i am wondering how the marker has been posted directly without adding to database. ? Could you elaborate please

    • Irina says

      I hope you like the google maps api. There are some pretty cool apps that can be built with it :)

  15. says

    Hello Irina,

    thank you so much for this blog. It has really opened my eyes. I have ended up on a page called MapedTravel some time ago and was since wondering how something like that could be achieved. (I have dabbled a little in Google Maps before, but nothing on this scale.) Now I have found this blog and it immediately hit home to me how something as complex as such a website could be approached.
    Thank you for your clear explanations. It helps us mere mortals understand the world a little better.

    Michael T

  16. Irina says

    I made one of the suggested improvements! Only one infowindow will be open at a time. When you open a new one, the last opened one is closed :)

  17. Omer Rosenbaum says

    Hi Irina!
    I installed the application on a local server and after I defined it and tried to pin my first location I got these errors:

    Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:Programsxampphtdocstravelmapindex.php on line 274
    Interactive Travel Map

    Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:Programsxampphtdocstravelmapindex.php on line 314

    I have no idea where I went wrong here… You help will be much appreciated.

  18. says

    Hi Irina!

    Another nice Google Maps API mashup by you, congrats!

    Only thing at first which is confusing me are infoWindows which are opening on marker hover and not closing the old one before opening the new one. So after hovering on several markers there is mass of opened infoWindows covering the map on each others top.

    • Irina says

      I’m glad you liked it!

      Yeah, I know it’s a bit odd, I wanted to make the windows show up when the users clicks on a marker, but I already used the click event to add a new address so I decide the use the mouseover one instead.

  19. Matt says

    Thanks for posting this. I was excited when I stumbled across this as it is potentially something we would like to develop for some of our clients. I’ve tried the demo in Google Chrome and it seems to be abit buggy – it’s quite hard to navigate with the mixture of mouse-over pointers. Some of the panes are bigger than the Google Map size which causes alot of jumping. Some of the content within the pane doesn’t appear within the tabs layout used in other panes. I can send screenshots if it would help.

    • Irina says

      The problem is with the sample code I used to create the tabbed infowindows. I’ll try and fix the problem.