Use PHP, MySql and Google Map API v3 for displaying data on map

Displaying multiple=Displaying data on maps can be useful in many situations.

By integrating tools like PHP, MySQL and Google Maps, you can relatively easy build customized maps for your website or blog.

In this post we’ll take a closer look on the possibilities, and build a  interactive map based on PHP, MySql and Google Map API v3.

To see what we’re building, see live example here

Geocoded data

The script in this post uses MySQL for storing the data that’s going to be displayed on the map. This method works fine if you’re adding multiple points to your map (10+), and want a dynamic way to retrieve data data. If you’re going to display less than 10 Points the solution in this post is a little overkill.

Before proceeding, you need some geocoded data (data that contains lat/long information) to display on the map. If you don’t have geocoded data, you can find a post here, where you can learn how to geocode addresses for usage on eg. Google Maps.

You can use the following test data for this example:

 `name` text NOT NULL,
 `desc` text NOT NULL,
 `lat` text NOT NULL,
 `lon` text NOT NULL,

-- Data dump for the table `poi_example`

INSERT INTO `poi_example` (`id`, `name`, `desc`, `lat`, `lon`) VALUES
(1, '100 Club', 'Oxford Street, London  W1<br/>3 Nov 2010 : Buster Shuffle<br/>', '51.514980', '-0.144328'),
(2, '93 Feet East', '150 Brick Lane, London  E1 6RU<br/>7 Dec 2010 : Jenny & Johnny<br/>', '51.521710', '-0.071737'),
(3, 'Adelphi Theatre', 'The Strand, London  WC2E 7NA<br/>11 Oct 2010 : Love Never Dies', '51.511010', '-0.120140'),
(4, 'Albany, The', '240 Gt. Portland Street, London  W1W 5QU', '51.521620', '-0.143394'),
(5, 'Aldwych Theatre', 'Aldwych, London  WC2B 4DF<br/>11 Oct 2010 : Dirty Dancing', '51.513170', '-0.117503'),
(6, 'Alexandra Palace', 'Wood Green, London  N22<br/>30 Oct 2010 : Lynx All-Nighter', '51.596490', '-0.109514');

When you have a MySQL database with Geocoded content you’re ready to proceed.

Extracting from MySQL

Next thing is to create a small piece of PHP that can connect and extract data from MySQL

// connection to mysql

$dbname            ='<database name>'; //Name of the database
$dbuser            ='<database username>'; //Username for the db
$dbpass            ='<database password>'; //Password for the db
$dbserver        ='<database server>'; //Name of the mysql server

$dbcnx = mysql_connect ("$dbserver", "$dbuser", "$dbpass");
mysql_select_db("$dbname") or die(mysql_error());

// extracting and looping through data

 $query = mysql_query("SELECT * FROM poi_example");
 while ($row = mysql_fetch_array($query)){
echo ("addMarker($lat, $lon,'<b>$name</b><br/>$desc');\n");

As you can see, the output of the script is has the following format: “addMarker(lat, long, marker data);“, this is the marker format that you can use for adding multiple markers fir Google Maps API V3.

Google Maps API V3

Next thing is to embed the PHP code into the javascript required for displaying multiple infowindows in Google Map API V3.

For this example, we have used the code from August LI as inspiration.

The script has the following features:

  • “var icon”: specifies a customizable icon. In this example a icon from Google is used, but you can add your own icons as well
  • “var popup”: specifies the maximum width of the info window. In this case 300 pixels
  • “addMarker”: contains latitude and longitude of the points, and a possibility to display whatever HTML content you like in the info window that corresponds to each point.   In this example we’re just displaying a headline and description
  • The map automatically zooms and centers to the most detailed view where all the map markers can be displayed in the same map. This is automatically calculated based on the size of the map, and the locations of the map markers.

The most important limit of this script is, that this technique is primarily useful to display a limited amount of map markers (below 100). If you’re going to display more points, you should consider a marker cluster solution.

The final script with the PHP and javascript code merged looks like this:

$dbname            ='insert mysql database name'; //Name of the database
$dbuser            ='insert mysql user name'; //Username for the db
$dbpass            ='insert mysql password'; //Password for the db
$dbserver          ='insert mysql database server address'; //Name of the mysql server

$dbcnx = mysql_connect ("$dbserver", "$dbuser", "$dbpass");
mysql_select_db("$dbname") or die(mysql_error());
 <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
 <title>Google Map API V3 with markers</title>
 <style type="text/css">
 body { font: normal 10pt Helvetica, Arial; }
 #map { width: 350px; height: 300px; border: 0px; padding: 0px; }
 <script src="" type="text/javascript"></script>
 <script type="text/javascript">
 //Sample code written by August Li
 var icon = new google.maps.MarkerImage("",
 new google.maps.Size(32, 32), new google.maps.Point(0, 0),
 new google.maps.Point(16, 32));
 var center = null;
 var map = null;
 var currentPopup;
 var bounds = new google.maps.LatLngBounds();
 function addMarker(lat, lng, info) {
 var pt = new google.maps.LatLng(lat, lng);
 var marker = new google.maps.Marker({
 position: pt,
 icon: icon,
 map: map
 var popup = new google.maps.InfoWindow({
 content: info,
 maxWidth: 300
 google.maps.event.addListener(marker, "click", function() {
 if (currentPopup != null) {
 currentPopup = null;
 }, marker);
 currentPopup = popup;
 google.maps.event.addListener(popup, "closeclick", function() {
 currentPopup = null;
 function initMap() {
 map = new google.maps.Map(document.getElementById("map"), {
 center: new google.maps.LatLng(0, 0),
 zoom: 14,
 mapTypeId: google.maps.MapTypeId.ROADMAP,
 mapTypeControl: false,
 mapTypeControlOptions: {
 style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
 navigationControl: true,
 navigationControlOptions: {
 style: google.maps.NavigationControlStyle.SMALL
 $query = mysql_query("SELECT * FROM poi_example");
 while ($row = mysql_fetch_array($query)){
 echo ("addMarker($lat, $lon,'<b>$name</b><br/>$desc');\n");
 center = bounds.getCenter();

 <body onload="initMap()" style="margin:0px; border:0px; padding:0px;">
 <div id="map"></div>

The final result looks like this:

Using Google Map API v3, php and mysql to display multiple=

See live example here


With the sample data and scripts in this post, you can easily get started working with multiple map markers on Google Map API V3. As mentioned earlier, the only limit in this script is that if performs best with < 100 markers at the same time.

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
fold-left fold-right
About the author
Jørgen Nicolaisen has been passionately interested in everything online since 1995. His experience is based on working with small hobby projects as well as high volume websites. Jørgen is currently focused on the PHP based programming framework - Codeigniter, and WordPress naturally

52 Replies to Use PHP, MySql and Google Map API v3 for displaying data on map

  1. Vikash says:

    Nice article for integrate the google map

  2. Sersh says:

    Awesome nice tut thank you! +10

  3. Sanya says:

    Why does example not work? (((

  4. alistair says:

    you need to remove the line:

    map.setZoom(map.getZoom – 1);

    in your live example, as it now won’t work with it – would
    give ‘too much recursion’ javascript error.

  5. ACC says:

    Even removing “map.setZoom(map.getZoom – 1);” does not seem to help.

  6. jhnidk says:

    A new version of the script has been uploaded – works fine now. Thank you for the feedback :-)

  7. jhnidk says:

    Thank you for the feedback – works fine now

  8. jhnidk says:

    It’s been updated, and works fine now

  9. Paul says:

    This works fine, except that changing the zoom level has no effect. I want it about 8, but I keep getting 14….

  10. Paul says:

    Thanks for this, it all works fine – except that I can’t get a different zoom level to work. No matter what I enter, I always get the max zoom. Any suggestions?

  11. jhnidk says:

    The code “map.fitBounds(bounds);” in line 78 ensures that the script automatically zooms to the most detailed zoom where all points can be seen in the same map. You should try to remove this to get a fixed zoom level.

  12. Alan says:

    Thanks a million. Screwed around for days with Flex trying to get something similar to work and after just two hours I have this example up and running with my data and my markers. Now to figure out how to get tabbed infowindows to work and then things should be hunky dory.

    To those who are having zoom problems as jhnidk says, the script zooms as needed-which is a nice feature.

  13. kevin says:

    Hello, I have been working through this tut for a few days now, and it has been the best google map tut for me. thanks for posting. I do have a question on how to change one section, you use php here:
    $query = mysql_query("SELECT * FROM poi_example");
    while ($row = mysql_fetch_array($query)){
    echo ("addMarker($lat, $lon,'$name$desc’);\n”);

    I would like to incorporate json instead, can you help me with this please?

    var map_list = ;

    for( var i = 0; i < map_list.length; i++ )
    var contacts_name = map_list[i]['first_name'];
    var contacts_lat = map_list[i]['lat'];
    var contacts_lon = map_list[i]['lon;];



  14. kevin says:


    Here is the proper json script:

    var map_list = ;

    for( var i = 0; i < map_list.length; i++ )
    var contact_name = map_list[i]['first_name'];
    var contact_lat = map_list[i]['lat'];
    var contact_lon = map_list[i]['lon;];


  15. Paul says:

    Removing the code “map.fitBounds(bounds);” doesn’t correct the zoom for me – it just moves the map a few hundred kilometers from the designated location.


  16. Paul says:

    And how do you make this open in a new, small popup window, complete with a close button, please?


  17. JP D says:

    What if you have a million of records on mysql and you only want to get all the locations that are in on the displayed map area?

  18. rajo says:

    Please, How to do every mark show a title, this title must be data of $name using tooltip. any idea? thanks

  19. AMJ says:

    Is there any way to change the icon depending on a particular condition? I have data stored in the MySQL table and would like to have different color markers display depending on the table data.

  20. David says:

    I struggle to add Clusterer. Any suggestions welcome. I can make clusterer V3 work OR I can read data from the DB per above, but I can not do both at the same time.

  21. Evans says:

    thanx alot for this post was searching for this for ages now..

  22. per says:

    Please I need use a differents type icons. I have a field in database with values such as restaurants, bar, cafe, etc how can I put this icons for every group? thanks

  23. Peter says:


    Great code! Was just what i was looking for. I need to adapt it slightly though, bascially i need to display a different colour pointer based on certain conditions of the sql query, does anyone know how i could go about doing this?


  24. Geekmate says:

    works perfectly!! thank you

  25. gdrako says:

    Very good article
    Has helped me a lot, but I have a problem with the zoom
    I use the above script to reflect only one point from the database.
    How I can change the zoom where I want ?

  26. Chris says:

    Thanks for some great code. I see that others are able to make this work, but I can not get the map and markers to display.

    I modified the php portion for the database and this working and verified.

    Howerver, no map appears.

    When I look at t the html source on the browser, all my data appears as echos. For some reason the echo doesn’t call addMarker, it outputs it as html instead. I have tried this with both FF and IE.

    Any help would be really appreciated.



  27. Kumar says:

    Hi i am using the above Gmap api v3 in my website. i have added more than ten address with lat and lang . but the markers for each address are not showing in the map . i get confused . what would be the problem ?
    I need immediate solution . I hope i would get reply soon .
    Thank you ..

  28. Sam says:

    Thanks for the tutorial, but i am having the same problem the page does not show the map. When i inspect in chrome it says , initMap is not defined and i guess the php code in the script is not rendering properly. Any help on the issue.

    Thanks again.

  29. Sam says:

    Ohh Never Mind, found the problem. the just added <?php on the first line instead of <? that made it to work. Thanks again.

  30. rav says:

    Thanks for the gr8 code. I have a similar problem like chris. I have created the database and changed the username, database name and password correctly.But could somebody kindly tell me how to save the finalcode- i mean should i save it as map.html or map.js. Because when i save it as map.html it just displays a blank web page. And if required to be saved as something else, how do i run it in the browser.
    Thanx for ur kind help in anticipation.

  31. Kris says:

    To the poster above – you really should know this already so I am just going to give a hint –

    How do you make sure that code with PHP in it is recognized as such?

  32. ilt says:

    Thanks for the example code. I have a database with some geocoded entries. How do I get the script to only try to plot the ones with a lat, log pair?

  33. jay says:

    Dear jhnidk, I was use u’re code for my application. But I have to modify it. I am using a form for search a location and then show it and other nearby location on the map. But the problem is, I have to different the color of searched location.

    I try to add a parameter to the addMarker function like this :
    function addMarker(lat, lng, var col, info)

    and I add argument when calling that function
    $col = “red”; //just example
    echo (“addMarker($lat, $lon, $col,’Location : $name’);\n”);

    But it dont result anything. Can you give me a solution please?

    Very thanks to you..

    Best regards

    #I’m Indonesian, sorry for my english

  34. George says:

    hm, very confused… i used this script on a shared web server at networksolutions and it worked great, no problems at all… and recently i changed over to a dedicated server at 1and1 and all of a sudden it stopped working, if there is supposed to be a marker on the map, the map goes blank and dissapears… if no markers on the map it loads the map just fine… any ideas? ive been on it for days thanks

  35. Nindya says:

    it’s not working..

  36. V says:

    Is there a way to turn this map to a satellite view?


  37. Chris says:

    Hi, I’m using this code, and it works great, thanks.
    Just one thing.
    I’m trying to change the zoom level, changing the value 14 to another. But he doesn’t seem to change the zoom level doing that…

  38. Chris says:

    Oh, sorry, saw the solution in the comments just now.

  39. Chris says:

    if I remove the line you suggested, map.fitBounds(bounds);, the map is centered around the marker anymore…

  40. pvr says:

    I copy above code and paste and change then code not work .Its not showing any error it only show blank page..

    Please reply
    Thanks Ad..

  41. Hemant Kumar says:

    Thanks map, awesome code. I have been looking for code for multiple marker in the Google API. But this one is simply awesome. Thanks a lot for writing it here.

    I just have one question, you have used fixed zoom size here. In my code I am using varying zoom size depending upon the condition (I am running the map on 5 different conditions). Google API is over-riding the zoom size when map load with the place markers. For example, when there is only 1 marker on map, Google set its zoom to max, i am supplying it to size 11. and when there are more markers, Google map find them all and set its center and zoom level on its own. This should be size 11 its self and map center should be what i am supplying it.

    Can we control this zoom overriding and map bounds?

  42. Hemant Kumar says:

    Can I call this map on another page using ajax? if so, can anyone tell me how to do it?

    Thanks in advance

  43. rscr says:

    tnks i also followed

  44. Hemant Kumar says:

    LatLngBounds is working well and calculating markers and auto zooming the map based on the number of markers in the view port. Even if I turn off the LatLngBounds, the map is still working in the same way.

    Is there any way to turn it off?

    I need my map to bring all markers in a particular region, even if the markers are spread out of that region (In case someone put wrong region in its profile). I am running php with javascript and using 5 conditions in my code depending upon which I am fetching different maps + values + zoom size. Independent of how many markers on my map, the zoom size and the map remains the same.

    Right now if there is no marker point in the map, the zoom size is what I am supplying here. But when the number of marker is 1, it over ride zoom and zoom in to max. Depending upon the number of markers its zoom size increasing drastically which is not good for my website.

    My code is working fine in Google Maps V2 but not in V3.

    Can someone help me about it?

    Thanks in Advance

  45. vrushali says:

    i cant see the google map at all

  46. Dylan says:

    Has anyone figured out how to fix the zoom??

  47. Ampped Aeon says:

    Is there a way to add clustering to this? Ive tried, and doesnt seem to work for me.

  48. Konrad says:

    I found this page two hours ago. I loaded the code for creating and populating the table poi_examle into SQL window within my phpMyAdmin. The table was created after clicking the button Go. Then I copied the entire code, saved it as a PHP file. I had to provide only four parameters: mySQL database name where the table was created, host (server) name (‘localhost’), user name (‘root’), and password (”). Did not work, nor error messages. No maps. Then after reading all the comments I changed two lines from >? to >?php. Two hours after finding this site my code works perfectly. Thanks!! Now I will substitute your table with mine.

Trackbacks for this post

  1. Google map zoom level |
  2. Google map zoom level |

Comments are now closed for this article.