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

Google Maps 存储用户添加的信息

2009-11-29

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.

当您创建MySQL表,您要特别注意LAT和LNG的属性。由于目前谷歌地图缩放功能,您应该只需要小数点后6位数字的精度。为了保持我们的存储空间表所需最低限度,您可以指定LAT和LNG属性花车大小(10,6)。这将让字段存储6位小数点后面,加上最多的前4位小数,例如-123.456789度。你的表也应该有一个id属性作为主键,和一个类型的属性来区分的餐厅和酒吧,我们将让用户选择从下拉的选项之一选择的形式。

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 用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):

首先,你应该放在一个单独的文件中的数据库连接信息。通常这是一个好主意时,你用PHP来访问数据库,它把一,你不会受到诱惑,分享您的机密文件资料。在地图API论坛,我们偶尔会看到有人不小心公布他们的数据库连接信息时,他们只是尝试调试他们的XML输出代码。该文件应该是这样的,但自己的数据库信息(phpsqlinfo_dbinfo.php)填写:

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

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)所示:

<?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());
}

// 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');",
         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());
}

?>  

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.

在创建地图和围绕它,你可以点击侦听指定的地图。在回调函数侦听器,创建一个在协调这项被点击的标记和属性设置拖动到“真正的GMarkerOptions”对象,你发送给构造函数。然后,点击指定监听到标记的持久性有机污染物在开放标记的信息窗口。信息窗口有一个与多个文本域,一个下拉,并保存表单的HTML按钮。每个表单输入了一个ID,并有一个按钮的OnClick侦听调用saveData函数,如下所述。

Saving the Data 保存数据

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

在saveData功能的信息窗口的按钮调用,您执行下列操作:

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

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

    <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"
            type="text/javascript"></script>
    <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>";

              marker.openInfoWindow(html);
            });
            map.addOverlay(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.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) {
          marker.closeInfoWindow();
          document.getElementById("message").innerHTML = "Location added.";
        }
      });
    }
    </script>

  </head>

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

</html>  

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

随机文章推荐
网站分类


注:如需转载本文,请注明出处(原文链接),谢谢。更多精彩内容,请进入简明现代魔法首页。

进入新博客
喜欢本文,就分享它吧
给我留言
您的名字:
您的邮件:
您的网站:


 

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

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