简明现代魔法 -> 软件项目 -> Google Maps 存储用户添加的信息

Google Maps 存储用户添加的信息


Objective 学习目的

Many developers use the Google Maps API to create mashups that enable users to add and annotate geographically located information. The most intuitive user interface for accomplishing that goal is to have the user first create a marker or poly, pop up a window with a form, then let the user fill out the form and press a 'save' button to close the info window. This is the method used, for instance, by Google's My Maps service. This tutorial will explain the concepts behind the HTML and JavaScript that make up the info-window editing user interface, as well as the PHP code that can be used to add the saved info window data into a MySQL database. Developers following this tutorial should have some HTML/JavaScript/Google Maps API experience, as well as PHP/MySQL knowledge.

许多开发人员使用了谷歌地图API来创建mashup,使用户能够添加和地理注释中的信息。为实现这一目标的最直观的用户界面是让用户首先创建一个标记或聚,弹出一个组成一个窗口,然后让用户填写表格,然后按下'保存'按钮来关闭消息窗口。这是所采用的方法,例如,在谷歌的我的地图服务。本教程将解释背后的HTML和JavaScript的概念构成的信息窗口编辑的用户界面,以及PHP代码可以用来添加到一个MySQL数据库保存信息窗口的数据。本教程之后应该有一定的HTML / JavaScript /谷歌地图API经验的开发人员,以及PHP / MySQL的知识。

Creating the table 创建数据库

When you create the MySQL table, you want to pay particular attention to the lat and lng attributes. With the current zoom capabilities of Google Maps, you should only need 6 digits of precision after the decimal. To keep the storage space required for our table at a minimum, you can specify that the lat and lng attributes are floats of size (10,6). That will let the fields store 6 digits after the decimal, plus up to 4 digits before the decimal, e.g. -123.456789 degrees. Your table should also have an id attribute to serve as the primary key, and a type attribute to distinguish between restaurants and bars, as we'll let users select one of those options from a drop-down select in the form.


CREATE TABLE `markers` (
  `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

Adding row data with PHP 用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've never written PHP to connect to a MySQL database, you should visit php.net and read up on mysql_connect, mysql_select_db, my_sql_query, and mysql_error.

在这一点上,你应该有一个空表命名的标记。现在,您需要写一些PHP的陈述,可以添加一个行与到URL传递的数据表。用在这里应该在两种功能PHP 4和PHP 5。如果您从未编写的PHP连接到MySQL数据库,你应该访问php.net和阅读mysql_connect,mysql_select_db,my_sql_query起来,mysql_error。

First, you should put your database connection information in a separate file. This is generally a good idea whenever you're using PHP to access a database, as it keeps your confidential information in a file that you won't be tempted to share. In the Maps API forum, we've occasionally had people accidentally publish their database connection information when they were just trying to debug their XML-outputting code. The file should look like this, but with your own database information filled in (phpsqlinfo_dbinfo.php):



Now, you can write the code that will do the fun stuff — inserting the row. In the PHP, first retrieve the user data passed in through the URL, then connect to your database and execute an "INSERT INTO" query on your table, passing in the user data. If there's an error along the way, output a message to the screen to help you debug what's going on. To test that this PHP script works correctly, visit the URL in the browser and append the necessary parameters, e.g.: http://yourdomain.com/phpsqlinfo_addrow.php?name=Best%20Bar%20Ever&address=123%20Main%20St&lat=-37.12345&lng=122.12345&type=bar

现在,您可以编写代码,也将这样做有趣的东西 - 插入行。在PHP中,首先检索该用户数据通过该网址,然后连接到您的数据库和您的表上执行的“插入”查询,在用户数据传递。如果有一个前进道路上的错误,输出到屏幕上的讯息,帮助您调试正在发生的事情。为了测试这个PHP脚本正常工作,请在浏览器的URL并追加必要的参数,例如: http://yourdomain.com/phpsqlinfo_addrow.php?name=Best%20Bar%20Ever&address=123%20Main%20St&lat=-37.12345&lng=122.12345&type=bar

If no error message is output to the screen, then the PHP worked. Just make sure to delete later the rows you added while debugging. The PHP file that does all that is shown below (phpsqlinfo_addrow.php):

如果没有错误信息输出到屏幕上,然后在PHP工作。请确定删除后,你说行调试时。 PHP文件但这一切低于(phpsqlinfo_addrow.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());

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

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

$result = mysql_query($query);

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


Creating the map & UI 创建地图和UI

Now that the backend functionality is setup, it's time to move onto creating the map and user interface functionality. If you have never created a Google Map, please try some of the basic examples in the documentation to make sure you understand the basics of creating a Google Map.


Creating the Marker + Info Window 创建标注和信息窗口

After creating the map and centering it, you can assign a click listener to the map. In the callback function to the listener, create a marker at the coordinate that was clicked and set the draggable property to "true" in the GMarkerOptions object you send in to the constructor. Then, assign a click listener to the marker that pops open an info window over the marker. The info window has the HTML for a form with several text fields, a drop down, and a save button. Each form input has an ID, and the button has an onclick listener to call the saveData function, described below.


Saving the Data 保存数据

In the saveData function that's called by the info window button, you do the following:


The HTML file that does this is shown below (phpsqlinfo_add.html):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<html xmlns="http://www.w3.org/1999/xhtml">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title>Google Maps JavaScript API Example: Simple Map</title>
    <script src="http://maps.google.com/maps?file=api&v=2.x&key=ABQIAAAAjU0EJWnWPMv7oQ-jjS7dYxTPZYElJSBeBUeMSX5xXgq6lLjHthSAk20WnZ_iuuzhMt60X_ukms-AUg"
    <script type="text/javascript">

    var marker;

    function initialize() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(37.4419, -122.1419), 13);

        GEvent.addListener(map, "click", function(overlay, latlng) {
          if (latlng) {
            marker = new GMarker(latlng, {draggable:true});
            GEvent.addListener(marker, "click", function() {
              var html = "<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 & Close' onclick='saveData()'/></td></tr>";



    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.getLatLng();
      var lat = latlng.lat();
      var lng = latlng.lng();

      var url = "phpsqlinfo_addrow.php?name=" + name + "&address=" + address +
                "&type=" + type + "&lat=" + lat + "&lng=" + lng;
      GDownloadUrl(url, function(data, responseCode) {
        if (responseCode == 200 && data.length <= 1) {
          document.getElementById("message").innerHTML = "Location added.";


  <body onload="initialize()" onunload="GUnload()">
    <div id="map_canvas" style="width: 500px; height: 300px"></div>
    <div id="message"></div>


The map should look like this, when the info window is opened:





copyright © 2009 简明现代魔法    学习、分享、进步

power by Gonn 感谢所有关心和支持本站的朋友们