Coding - Databases - PHP

PHP and MySQL: Working with Google Maps

Maps are perfect examples of modern web philosophy, visually representing data and also taking advantage of the mobile web by allowing sites and apps to be customized by location. Not every web application needs maps, but they can enhance many of them.

Just as it has with search, Google has all but cornered the market in online mapping. There are other players (Yahoo, Bing, etc), but the vast majority of online map users are using Google Maps, so if you are programming a map into your site or app, you can’t avoid working with Google.> The good news is, Google’s Maps API is actually quite user friendly and easy to integrate into a PHP / MySQL application. This lesson is going to walk you through using PHP and MySQL with Google Maps to create maps that are attractive, useful, and customizable.

Getting Started

For this tutorial, I’m going to assume that you have PHP and MySQL installed, and that you’ve done some basic programming with both. If you’re brand new to both programs, you can check out our Introduction to PHP and PHP Basics: MySQL tutorials to get up to speed.

The other thing that you’ll need to get started with Google Maps is a Google API key. This is a long alphanumeric code that allows you access to Google’s API code. To get an API key, go to this page. If you have a Google account (through GMail or another Google service) already, then it’s pretty much a one-click process.

Prepping Your Database for Mapping

In order to use PHP and MySQL to build dynamic maps for your application, you’ll need database tables to store the geographic information that will be displayed on the map. There are several ways to go about this, but here is an example that will work for our purposes. First, put the following code in a new PHP file, called connect.php:

    $con = new mysqli("localhost", "user", "password", "databasename");

    if($con->connect_errno > 0){
      die('Unable to connect to database [' . $con->connect_error . ']');

If you took our PHP Basics: MySQL tutorial (LINK), you’ll recognize this code as the same MySQL connection code that we used there. Replace the host, user, password, and databasename variables with the correct ones for your database, and your connection script should be good to go.

Next, start another new PHP file, and call this one create.php. This is where we’re going to set up our data tables to populate our map:


    include 'connect.php';
    $createmaptable = 'CREATE TABLE IF NOT EXISTS maps (
	centerLat decimal (5,3),
        centerLong decimal (6,3),
        zoom  tinyint

    if(!$result = $con->query($createmaptable)){
      die('There was an error running the query [' . $con->error . ']');

    $createmappointtable = 'CREATE TABLE IF NOT EXISTS mappoints (
        mapID int, 
	pointLat decimal (5,3),
        pointLong decimal (6,3),
        pointText text

    if(!$result = $con->query($createmappointtable)){
      die('There was an error running the query [' . $con->error . ']');


We’re using a MySQL data type in these tables that we didn’t cover in the PHP Basics tutorial on MySQL, namely the decimal type. When declaring a decimal field in our database tables, we set two attributes: the total number of decimal places and the number of places after the decimal point. So, we create the field for the latitude of our map’s center with centerLat decimal (5,3), because latitudes can only range from -90 to 90 degrees (2 places), and we want a precision of three decimal places after the decimal point. Since longitudes can range over 100 or under -100, we need to add an extra place for the longitude fields.

Adding Some Data

Now we have two new database tables, one to hold data on maps (lat and long of center point and zoom level) and one to hold individual mapping points (again, a lat and long for each, and a text description). Now we need to populate these tables with some test data so we have something to work with.

Add the following code to the end of create.php, inside the closing ?> tag:

   $maps = array(
     array(1, 45.52, -122.682, 9), 
     array(2, -33.98, 18.424, 10), 
     array(3, 57.48, -4.225, 12)

   $mappoints = array(
     array(1, 45.249, -122.897, "Champoeg State Park"), 
     array(1, 45.374, -121.696, "Mount Hood"), 
     array(2, -33.807, 18.366, "Robben Island"), 
     array(2, -33.903, 18.411, "Cape Town Stadium"), 
     array(3, 57.481, -4.225, "Inverness Bus Station"), 
     array(3, 57.476, -4.226, "Inverness Castle"), 
     array(3, 57.487, -4.139, "The Barn Church") 

   foreach ($maps as $ind) {
     $newline = "INSERT INTO maps 
       (ID, centerLat, centerLong, zoom) 
       VALUES ($ind[0], $ind[1], $ind[2], $ind[3])";

     if(!$insertmap = $con->query($newline)){
       die('There was an error running the query [' . $con->error . ']');

   foreach ($mappoints as $indpt) {
     $newline = "INSERT INTO mappoints 
       (mapID, pointLat, pointLong, pointText) 
       VALUES ($indpt[0], $indpt[1], $indpt[2], '$indpt[3]')";

     if(!$insertmap = $con->query($newline)){
       die('There was an error running the query [' . $con->error . ']');

This script creates two arrays, one holding three rows of map data, the other holding seven map points, then enters them into their respective data tables. Run all of create.php by loading the page in your browser. You’ll notice that if you try to load the page twice, it will create an error, since the IDs for each map are already set. This is because of the PRIMARY KEY we set on the ID column of the table maps, which ensures that each row has a unique ID.

Your First Map

All right. We have tables, we have data. Now it’s time to build our first map. Enter the following code into a new file, called map.php:


  include 'connect.php';

  $apikey = "your_key_here";
  $id = $_GET['id'];

  $lat = 0;
  $long = 0;
  $zoom = 8;

  $findmap = "SELECT centerLat, centerLong, zoom FROM maps WHERE ID = $id";

  if(!$result = $con->query($findmap)){
     die('There was an error running the query [' . $con->error . ']');
  } else {
    $row = $result->fetch_assoc();
    $lat = $row['centerLat'];
    $long = $row['centerLong'];
    $zoom = $row['zoom'];

?><!DOCTYPE html>
    <meta name="viewport" 
        content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map-canvas { height: 100% }
    <script type="text/javascript"
          <?php echo $apikey; ?>&sensor=false">
    <script type="text/javascript">
      function initialize() {
        var mapOptions = {
          center: new google.maps.LatLng(<?php echo $lat.', '.$long; ?>),
          zoom: <?php echo $zoom; ?>
        var map = new google.maps.Map(document.getElementById("map-canvas"),
      google.maps.event.addDomListener(window, 'load', initialize);
    <div id="map-canvas"/>

Make sure you replace the value of the $apikey variable with your own API key.

The HTML portion of this page (from <!DOCTYPE to </html>) is provided by Google, and is the simplest code possible for displaying a basic map. The PHP we’ve added at the top of the script queries your database, selects the map details to match whatever map ID has been specified, and sets them into variables for the map to use. Notice that if you load the page map.php, you will get an error, since the page requires the id variable to be set. Try loading map.php?id=1, and a map of Portland, OR should display. Try map.php?id=2 and map.php?id=3 for maps of two of my other favorite cities in the world.

Setting Map Points

Raw maps are great if you just want to show your site’s visitors a specific part of the world, but Google Maps are infinitely more useful with map points added. Add this bit of code into map.php right after mapOptions);, and the map points that we set in our database table will show up in each of our example maps:

  $getpoints = "SELECT pointLat, pointLong, pointText 
      FROM mappoints WHERE mapID = $id";

  if(!$result = $con->query($getpoints)){
    die('There was an error running the query 
        [' . $con->error . ']');
  } else {
    while ($row = $result->fetch_assoc()) {
      echo '  var myLatlng1 = new google.maps.LatLng('.
          $row[pointLat].', '.$row[pointLong].'); 
  var marker1 = new google.maps.Marker({ 
    position: myLatlng1, 
    map: map, 

Take a look again at all three example maps. One of them should look pretty much like this:


The map points will show up as red pins, and when you hover your cursor over each one, the name of the place will appear. Congratulations. You’ve just made a dynamic Google Map!

Advanced Techniques

This has been a tutorial on creating the most basic Google Map, but the API includes functions that can do much more. Some examples of ways that you can make your maps even more useful:

  • Custom map icons (instead of the standard red pin)
  • Polygons and routes, to give directions and highlight areas of the map
  • Popup windows and links (adding more functionality to your map)

Keep playing with the code and use it to make your own Google Maps, then dig into these and other advanced API features. Happy programming!

About the author

Ian Rose is a web developer, blogger, and writer living in Portland, OR. In his day job, he develops WordPress plugins and custom PHP solutions, focusing on nonprofit clients. By night, he attempts to write both fiction and nonfiction. Ian's site is Seaworthy Web Solutions

Share this post


  1. Renato

    Hi Ian…how are you??

    I’m in trouble, I followed your tutorial step by step and my map was not generated.
    Can you post/send your code “working” for me?

    Thank You!

  2. Bas M

    Hi Ian,
    Can you tell me how i get an own api key?
    Gr. Bas

  3. Bas M

    I have it allready!
    It works :-)

  4. Arif Syatri

    omg it works,. thank you sir :)

  5. Hi Ian,

    It does not work for me! The last script after mapOptions); has troubles! Can you please post the solution?


  6. This is how it works for me:

    die(‘There was an error running the query
    [' . $con->error . ']‘);

    else {
    while ($row = $result->fetch_assoc()) {
    echo “var myLatlng1 = new google.maps.LatLng($row[pointLat], $row[pointLong]);
    var marker1 = new google.maps.Marker({
    position: myLatlng1,
    map: map,
    title: ‘$row[pointText]‘


  7. chifundo

    i am unable to get it right, can you send me the working code please

Leave a Comment

Subscribe To Our Newsletter