You're all set!

To start developing, please head over to our developer documentation.

Activate the Google Maps JavaScript API

To get you started we'll guide you through the Google Developers Console to do a few things first:

  1. Create or choose a project
  2. Activate the Google Maps JavaScript API and related services
  3. Create appropriate keys
Continue

From Info Windows to a Database: Saving User-Added Form Data

Overview

This tutorial shows you how to use the Google Maps JavaScript API to allow users to add information about a place to your map, and save this information to a MySQL database. It suits people with intermediate knowledge of HTML, JavaScript, PHP and MySQL.

Use the map below to try out the concepts in this tutorial. Click a location on the map to create a marker, and then click the marker to display an info window with a form to which you can add place information. Click the 'Save' button to display a confirmation when the map has saved the location details to a database.

Note that the map above is a demo to illustrate the concepts in this tutorial, and does not actually save locations to a database.

The sample below shows the entire code you need to create a map that can save locations to a database using PHP and MySQL. Hover at top right of the code block to copy the code.

<!DOCTYPE html >
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>From Info Windows to a Database: Saving User-Added Form Data</title>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map" height="460px" width="100%"></div>
    <div id="form">
      <table>
      <tr><td>Name:</td> <td><input type='text' id='name'/> </td> </tr>
      <tr><td>Address:</td> <td><input type='text' id='address'/> </td> </tr>
      <tr><td>Type:</td> <td><select id='type'> +
                 <option value='bar' SELECTED>bar</option>
                 <option value='restaurant'>restaurant</option>
                 </select> </td></tr>
                 <tr><td></td><td><input type='button' value='Save' onclick='saveData()'/></td></tr>
      </table>
    </div>
    <div id="message">Location saved</div>
    <script>
      var map;
      var marker;
      var infowindow;
      var messagewindow;

      function initMap() {
        var california = {lat: 37.4419, lng: -122.1419};
        map = new google.maps.Map(document.getElementById('map'), {
          center: california,
          zoom: 13
        });

        infowindow = new google.maps.InfoWindow({
          content: document.getElementById('form')
        });

        messagewindow = new google.maps.InfoWindow({
          content: document.getElementById('message')
        });

        google.maps.event.addListener(map, 'click', function(event) {
          marker = new google.maps.Marker({
            position: event.latLng,
            map: map
          });


          google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map, marker);
          });
        });
      }

      function saveData() {
        var name = escape(document.getElementById('name').value);
        var address = escape(document.getElementById('address').value);
        var type = document.getElementById('type').value;
        var latlng = marker.getPosition();
        var url = 'phpsqlinfo_addrow.php?name=' + name + '&address=' + address +
                  '&type=' + type + '&lat=' + latlng.lat() + '&lng=' + latlng.lng();

        downloadUrl(url, function(data, responseCode) {

          if (responseCode == 200 && data.length <= 1) {
            infowindow.close();
            messagewindow.open(map, marker);
          }
        });
      }

      function downloadUrl(url, callback) {
        var request = window.ActiveXObject ?
            new ActiveXObject('Microsoft.XMLHTTP') :
            new XMLHttpRequest;

        request.onreadystatechange = function() {
          if (request.readyState == 4) {
            request.onreadystatechange = doNothing;
            callback(request.responseText, request.status);
          }
        };

        request.open('GET', url, true);
        request.send(null);
      }

      function doNothing () {
      }

    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>

Getting started

Install and configure a MySQL server with PHP on your machine.

Creating a table in MySQL

Create a table in MySQL containing attributes of the markers on the map, like the marker id, name, address, lat, lng, and type.

The id attribute serves as the primary key, and the type attribute distinguishes between restaurants and bars. lat and lng represent the latitude and longitude attributes of the markers.

To keep the storage space for your table at a minimum, you can specify the lat and lng attributes to be floats of size (10,6). This allows the fields to store 6 digits after the decimal, plus up to 4 digits before the decimal.

You can interact with the MySQL database through the phpMyAmin interface. The screenshot below displays the table setup in phpMyAdmin.

You can also use SQL commands to create the table, as in the SQL statement below.

CREATE TABLE `markers` (
  `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
  `name` VARCHAR( 60 ) NOT NULL ,
  `address` VARCHAR( 80 ) NOT NULL ,
  `lat` FLOAT( 10, 6 ) NOT NULL ,
  `lng` FLOAT( 10, 6 ) NOT NULL ,
  `type` VARCHAR( 30 ) NOT NULL
) ENGINE = MYISAM ;

Adding row data with PHP

At this point, you should have an empty table named markers. You now need to write some PHP statements that can add a row to the table with data passed into the URL. The functions used here should work in both PHP 4 and PHP 5.

If you have never used PHP to connect to a MySQL database, visit php.net and read up on mysql_connect, mysql_select_db, my_sql_query, and mysql_error.

When using a public browser to access a database using PHP files, it's important to ensure that your database credentials are secure. You can do this by putting your database connection information in a separate PHP file to that of the main PHP code. The file with your credentials should look like the one below, but containing your own database information.

<?php
$username="username";
$password="password";
$database="username-databaseName";
?>

Below is the PHP file that connects to your MySQL database, and adds location information from your website.

<?php
require("phpsqlinfo_dbinfo.php");

// Gets data from URL parameters.
$name = $_GET['name'];
$address = $_GET['address'];
$lat = $_GET['lat'];
$lng = $_GET['lng'];
$type = $_GET['type'];

// Opens a connection to a MySQL server.
$connection=mysql_connect ("localhost", $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}

// Sets the active MySQL database.
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}

// Inserts new row with place data.
$query = sprintf("INSERT INTO markers " .
         " (id, name, address, lat, lng, type ) " .
         " VALUES (NULL, '%s', '%s', '%s', '%s', '%s');",
         mysql_real_escape_string($name),
         mysql_real_escape_string($address),
         mysql_real_escape_string($lat),
         mysql_real_escape_string($lng),
         mysql_real_escape_string($type));

$result = mysql_query($query);

if (!$result) {
  die('Invalid query: ' . mysql_error());
}

?>

The PHP code above first retrieves the place data that passes in through the URL, and then connects to the MySQL database. It then executes an "INSERT INTO" query on your MySQL table, passing in the place data.

To test that this PHP script works correctly, copy the URL below into your browser's address bar and append the necessary parameters, substituting 'yourdomain' with the name of your website.

http://yourdomain.com/phpsqlinfo_addrow.php?name=Best%20Bar%20Ever&address=123%20Main%20St&lat=-37.12345&lng=122.12345&type=bar

Your PHP code works if the output screen displays no error messages. Delete any additional rows in your MySQL table that the debugging process may have added.

Creating the map

This section shows you how to develop the map, and its user interface funtionality. Read the documentation to learn more about the basics of creating a Google map.

Create a new file in a text editor and save it as index.html. Read the sections that follow to understand the code that you can add to this file.

Setting up a basic map

This section explains the code that sets up a basic map. This may be similar to how you created maps when getting started with the Google Maps JavaScript API.

Try it yourself

Copy the code below into your index.html file to display a basic Google map.

<!DOCTYPE html>
<html>
  <head>
    <style type="text/css">
      #map {
        height: 100%;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
    var map;

    function initMap() {
        var california = {lat: 37.4419, lng: -122.1419};
        map = new google.maps.Map(document.getElementById('map'), {
          center: california,
          zoom: 13
        });
    }
    </script>
    <script async defer
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap>
    </script>
  </body>
</html>

Click YOUR_API_KEY in the code sample, or follow the instructions to get an API key. Replace YOUR_API_KEY with your application's API key.

Creating the markers and info windows

The sections that follow show you how to create the markers and info windows that appear as the user interacts with the map.

Defining variables

The code below defines variables for the map, markers, the info window with the form, and the info window with the 'Location saved' confirm message.

var map;
var marker;
var infowindow;
var messagewindow;

Define these variables outside theinitMap function.

The code below creates a div that defines the HTML for the info window form fields.

<div id="table">
<table>
<tr><td>Name:</td> <td><input type='text' id='name'/> </td> </tr>
<tr><td>Address:</td> <td><input type='text' id='address'/> </td> </tr>
<tr><td>Type:</td> <td><select id='type'> +
           <option value='bar' SELECTED>bar</option>
           <option value='restaurant'>restaurant</option>
           </select> </td></tr>
           <tr><td></td><td><input type='button' value='Save' onclick='saveData()'/></td></tr>
</table>
</div>

The div below defines the info window text that displays on saving the info window form.

<div id="message">Location saved</div>
Creating new objects for the info windows

Define the objects for the info windows within the initMap function.

The code below creates a new info window object that retrieves the form element on clicking a marker.

infowindow = new google.maps.InfoWindow({
  content: document.getElementById('form')
});

The code below creates a new info window object that retrieves the message element on saving the info window form.

messagewindow = new google.maps.InfoWindow({
  content: document.getElementById('message')
});
Defining click listeners

The code below assigns a click listener to the map with the addListener() callback function that creates a marker when the user clicks the map.

google.maps.event.addListener(map, "click", function(event) {
    marker = new google.maps.Marker({
      position: event.latLng,
      map: map
    });
});

The code below assigns a click listener to the marker which displays an info window when the user clicks the marker.

google.maps.event.addListener(marker, "click", function() {
  infowindow.open(map, marker);
});

Each form input has an ID, and the button has a click listener to call the saveData() function.

Saving data from the info window form

This section explains the code that saves the data entered by the user in the info window form.

Below is the code within the saveData function.

function saveData() {
  var name = escape(document.getElementById("name").value);
  var address = escape(document.getElementById("address").value);
  var type = document.getElementById("type").value;
  var latlng = marker.getPosition();
  var url = "phpsqlinfo_addrow.php?name=" + name + "&address=" + address +
            "&type=" + type + "&lat=" + latlng.lat() + "&lng=" + latlng.lng();

  downloadUrl(url, function(data, responseCode) {

    if (responseCode == 200 && data.length <= 1) {
      infowindow.close();
      messagewindow.open(map, marker);
    }
  });
}

The saveData code above performs the following operations:

  • Saves the name, address, location type (whether a bar or restaurant), and marker coordinates entered by the user in the info window form.
  • Constructs a URL by concatenating the name of the PHP file with the parameters and their values.
  • Passes the URL as the first parameter of downloadUrl(), which is a simple function that wraps the XMLHTTPRequest object that retrieves files (commonly in XML format) via JavaScript. The downloadUrl() callback function provides the content of the URL and the status code. If you use a framework like jQuery or YUI, you may want to replace this function with their respective wrapper functions.
  • Checks if the return status code is 200, which means that the XMLHTTPRequest object has retrieved the file successfully.
  • Checks the length of the data string that returns. An empty data file indicates that the request generated no error strings. If the length is zero, a success message appears when the user clicks the 'Save' button on the info window form.

More information

Now that you have a basic running example of adding user-annotated data from a Google Map into your database, you can add many more features like the ones below:

发送以下问题的反馈:

此网页
Google Maps JavaScript API
Google Maps JavaScript API
需要帮助?请访问我们的支持页面