Google Maps 使用PHP/MySQL

孔甫
2023-12-01

Google Maps 使用PHP/MySQL

2009-11-30

 

This tutorial is intended for developers who are familiar with PHP/MySQL, and want to learn how to use Google Maps with a MySQL database. After completing this tutorial, you will have a Google Map based off a database of places. The map will differentiate between two types of places—restaurants and bars—by giving their markers distinguishing icons. An info window with name and address information will display above a marker when clicked.

本教程是适合熟悉 PHP / MySQL,并想学习如何使用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.

 

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


Note: This tutorial uses location data that already have latitude and longitude information needed to plot corresponding markers. If you're trying to use your own data that don't yet have that information, use a batch geocoding service to convert the addresses into latitudes/longitudes. Some sites make the mistake of geocoding addresses each time a page loads, but doing so will result in slower page loads and unnecessary repeat geocodes. It's always better to hardcode the latitude/longitude information when possible. This link contains a good list of geocoders: http://groups.google.com/group/Google-Maps-API/web/resources-non-google-geocoders

 

If you don't have access to phpMyAdmin or prefer using SQL commands instead, here's the SQL statement that creates the table (phpsqlajax_createtable.sql):

如果您没有获得phpMyAdmin或者喜欢使用SQL命令代替,这里的SQL语句创建表(phpsqlajax_createtable.sql):

 

Populating the table 填充数据库

After creating the table, it's time to populate it with data. Sample data for 10 Seattle places are provided below. In phpMyAdmin, you can use the IMPORT tab to import various file formats, including CSV (comma-separated values). Microsoft Excel and Google Spreadsheets both export to CSV format, so you can easily transfer data from spreadsheets to MySQL tables through exporting/importing CSV files. Here's the sample data in CSV format (phpsqlajax_data.csv):

在创建表,现在是时候用数据填充它。 10西雅图地区样本数据如下。在phpMyAdmin的,您可以使用导入标签导入各种文件格式,包括CSV(逗号分隔值)。 Microsoft Excel和谷歌电子表格都出口到CSV格式,因此您可以方便地将电子表格数据到MySQL通过输出表/导入CSV文件。

Outputting XML with PHP 用PHP输出XML

At this point, you should have a table named markers filled with sample data. You now need to write some PHP statements to export the table data into an XML format that our map can retrieve through asynchronous JavaScript calls. 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语句导出到XML格式的表格数据,我们的地图可以检索通过异步JavaScript调用。如果您从未编写的PHP连接到MySQL数据库,你应该访问php.net和阅读mysql_connect,mysql_select_db,my_sql_query起来,mysql_error。

Note: Some tutorials may suggest actually writing your map page as a PHP file and outputting JavaScript for each marker you want to create, but that technique can be problematic. By using an XML file as an intermediary between our database and our Google Map, it makes for a faster initial page load, a more flexible map application, and easier debugging. You can independently verify the XML output from the database and the JavaScript parsing of the XML. And at any point, you could even decide to eliminate your database entirely and just run the map based on static XML files.

注意:有些教程其实可以书面提出一个PHP文件和输出的JavaScript网页为您的地图标记每个要创建,但这种技术可能会产生问题。通过使用作为一个与我们的数据库和我们的谷歌地图中间一个XML文件,它使更快的页面加载初期,更灵活的地图应用程序,且更加便于调试。您可以独立核实,并从数据库中的XML的JavaScript解析XML输出。在任何时候,你甚至可以决定完全消除您的数据库上运行,只是静态的XML文件为基础的地图。

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 (phpsqlajax_dbinfo.php):

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

  

 

Using PHP's domxml functions to output XML


Check your configuration or try initializing a domxml_new_doc() to determine if your server's PHP has dom_xml functionality on. If you do have access to dom_xml functions, you can use them to create XML nodes, append child nodes, and output an XML document to the screen. The dom_xml functions take care of subtleties such as escaping special entities in the XML, and make it easy to create XML with more complex structures.

检查您的配置或尝试初始化domxml_new_doc()来确定您的服务器的PHP已经dom_xml功能上。如果您可以访问dom_xml功能,可以使用它们来创建XML节点,添加子节点,并输出一个XML文档到屏幕上。该dom_xml职能照顾细微的照顾,如逃脱在XML中有特殊的实体,可以很容易地创建具有更复杂的结构的XML。

In the PHP, first initialize a new XML document and create the "markers" parent node. Then connect to the database, execute a SELECT * (select all) query on the markers table, and iterate through the results. For each row in the table (each location), create a new XML node with the row attributes as XML attributes, and append it to the parent node. Then dump the XML to the screen.

在PHP中,首先初始化一个新的XML文档,并创建“标志”的父节点。然后连接到数据库,执行SELECT *(选择所有的标记表)查询,并遍历结果。对于每个表中(每个位置),创建一个新的行与行的XML节点属性的XML属性,并追加到父节点。然后将XML转储到屏幕上。

 

Note: If your database contains international characters or you otherwise need to force UTF-8 output, you can use utf8_encode on the outputted data. The PHP file that does all that is shown below (phpsqlajax_genxml.php):

注意:如果您的数据库包含国际字符或者其他需要强制的UTF - 8输出,您可以使用输出数据函数utf8_encode。 PHP文件但这一切低于(phpsqlajax_genxml.php)所示:

 

Using PHP's echo to output XML

If you don't have access to PHP's dom_xml functions, then you can simply output the XML with the echo function. When using just the echo function, you'll need to use a helper function (e.g. parseToXML) that will correctly encode a few special entities (<,>,",') to be XML friendly.

如果您没有获得PHP的dom_xml功能,那么你可以简单地输出与回声功能的XML。当只使用回声功能,您将需要使用一个辅助功能(如parseToXML),将正确编码数(<,>,",')特殊的实体是XML的友好。

In the PHP, first connect to the database and execute the SELECT * (select all) query on the markers table. Then echo out the parent markers node, and iterate through the query results. For each row in the table (each location), you need to echo out the XML node for that marker, sending the name and address fields through the parseToXML function first in case there are any special entities in them. Finish the script by echoing out the closing markers tag.

在PHP中,第一次连接到数据库,并执行SELECT *(选择所有的标记表)查询。然后回声出父标记节点,遍历查询结果。对于每个表中(每个位置)行,你需要回应了该标记的XML节点,通过parseToXML发送函数的第一个名称和地址领域的情况下对他们有任何特殊的实体。完成呼应了结束标记标记脚本。

Note: If your database contains international characters or you otherwise need to force UTF-8 output, you can use utf8_encode on the outputted data. The PHP file that does all this is shown below (phpsqlajax_genxml2.php):

注意:如果您的数据库包含国际字符或者其他需要强制的UTF - 8输出,您可以使用输出数据函数utf8_encode。 的PHP文件,这一切说明如下(phpsqlajax_genxml2.php)所示:

 

Using PHP's DOM functions to output XML

First, check your configuration and make sure you are using PHP5. If you aren't, then use one of the previous techniques.

首先,检查您的配置,并确保您使用的是PHP5的。如果你没有,然后使用以前的技术之一。

In PHP, first initialize a new XML document and create the "markers" parent node. Then connect to the database, execute a SELECT * (select all) query on the markers table, and iterate through the results. For each row in the table (each location), create a new XML node with the row attributes as XML attributes, and append it to the parent node. Then dump the XML to the screen.

在PHP中,首先初始化一个新的XML文档,并创建“标志”的父节点。然后连接到数据库,执行SELECT *(选择所有的标记表)查询,并遍历结果。对于每个表中(每个位置),创建一个新的行与行的XML节点属性的XML属性,并追加到父节点。然后将XML转储到屏幕上。

Note: If your database contains international characters or you otherwise need to force UTF-8 output, you can use utf8_encode on the outputted data. The PHP file that does all this is shown below (phpsqlajax_genxml3.php):

注意:如果您的数据库包含国际字符或者其他需要强制的UTF - 8输出,您可以使用输出数据函数utf8_encode。 的PHP文件,这一切说明如下(phpsqlajax_genxml3.php)所示:

 

Checking that XML output works

Call this PHP script from the browser to make sure it's producing valid XML. If you suspect there's a problem with connecting to your database, you may find it easier to debug if you remove the line in the file that sets the header to the text/xml content type, as that usually causes your browser to try to parse XML and may make it difficult to see your debugging messages.

从浏览器调用这个PHP脚本,以确保它的生产有效的XML。如果您怀疑有问题的连接到您的数据库,您可能会发现更容易调试如果删除该文件中的行头设置文本/ XML内容类型,通常导致您的浏览器,试图解析XML并可能难以看到您的调试信息。

If the script is working correctly, you should see XML output like this (phpsqlajax_expectedoutput.xml):

如果脚本是否工作正常,您应该看到这样的(phpsqlajax_expectedoutput.xml XML输出):


 

Creating the map 创建地图

Once the XML is working in the browser, it's time to move on to actually creating the map with JavaScript. 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.

一旦XML是工作在浏览器,现在是时候继续前进,以实际使用JavaScript创建地图。如果您从未创建了谷歌地图,请尝试在文件中的一些基本的例子,以确保您了解创建一个谷歌地图的基础知识。

Loading the XML file

To load the XML file into our page, you can take advantage of the API function GDownloadURL. GDownloadURL is a wrapper for the XMLHttpRequest that's used to request an XML file from the server where the HTML page resides. The first parameter to GDownloadURL is the path to your file—it's usually easiest to have the XML file in the same directory as the HTML so that you can just refer to it by filename. The second parameter to GDownloadURL is the function that's called when the XML is returned to the JavaScript.

加载到我们的页面的XML文件,您可以利用API函数GDownloadURL优势。 GDownloadURL是一个XMLHttpRequest的包装器的使用要求,从服务器的XML文件,其中的HTML页所在。第一个参数GDownloadURL是您的文件的路径,它通常是最有作为,在同一目录中的XML的HTML文件,以便你可以参考它的文件名。第二个参数GDownloadURL的是,被称为当XML返回到JavaScript函数。

Note: It's important to know that GDownloadURL is asynchronous—the callback function won't be called as soon as you invoke GDownloadURL. The bigger your XML file, the longer it may take. Don't put any code after GDownloadURL that relies on the markers existing already—put it inside the callback function instead.

注:重要的是要知道GDownloadURL是异步回调函数不会被调用只要你调用GDownloadURL。较大的XML文件时,可能需要更长。不要把任何代码后GDownloadURL,在现行的已标记的作用,依靠放进回调函数来代替它。

In the callback function, you need to find all the "marker" elements in the XML, and iterate through them. For each marker element you find, retrieve the name, address, type, and lat/lng attributes and pass them to createMarker, which returns a marker that you can add to the map.

在回调函数中,你需要找到所有的“标志”的XML元素,并通过他们迭代。对于每一个标记元素您查找,检索的名称,地址,类型和纬度/液化天然气的属性,并通过他们createMarker,它返回一个标记,您可以添加到地图上。

 


Creating custom icons

You can use the GIcon class to define custom icons which can later be assigned to the markers. Start by declaring two GIcon objects—iconBlue and iconRed—and define their properties.

您可以使用GIcon类定义自定义,可后来被分配到标记图标。开始申报两个GIcon对象iconBlue和iconRed,并确定其性质。

Warning: You may get away with specifying fewer properties than in the example, but by doing so, you run the risk of encountering peculiar errors later.

 

警告:你可以逃脱指定比例子较少属性,但这样做,您运行后遇到的特殊错误的风险。

You then create an associative array which associates each GIcon with one of your type strings: 'restaurant' or 'bar.' This makes the icons easy to reference later when you create markers from the XML.

然后,创建一个关联数组的赞同你的类型每个GIcon字符串之一:'餐厅'或'吧。这使得图标容易引用后,当您创建的XML标记。


Creating markers & info windows

You should have all your marker creation code in a createMarker function. You can retrieve the appropriate GIcon by using the type as the key for the associative array that was globally defined, and pass that into the GMarker constructor. Then, construct the HTML that you want to show up in the info window by concatenating the name, address, and some tags to bold the name.

你应该都在createMarker功能您的标记,创建代码。您可以通过使用作为关联数组是全局定义的关键键入相应的GIcon,并传递到GMarker构造。然后,构造的HTML要显示在信息窗口由串联的名称,地址,以及一些大胆的名称标签。

Tip: Some tutorials instruct you to store HTML-formatted descriptions in your database, but doing so means you then have to deal with escaping HTML entities, and you'll be bound to that HTML output. By waiting until you've retrieved each attribute separately in the JavaScript, you are free to play around with the HTML on the client side and can quickly preview new formatting.

提示:有些教程指导你存储HTML格式的数据库中的描述,但这样做意味着你便要处理逃脱HTML实体,你会被绑定到该HTML输出。通过等待,直到您检索每个属性分别在JavaScript,您可以自由地发挥与客户端的HTML左右,可以快速预览新的格式。

After constructing the HTML string, add an event listener to the marker so that when clicked, an info window is displayed.

建设后的HTML字符串,添加一个事件监听器的标记,以便当点击,一个信息窗口。

 

 

 

Putting it all together

Here's the web page that ties the markers, icons, and XML together. When the page loads, the load function is called. This function sets up the map and then calls GDownloadUrl. Make sure your GDownloadUrl is passing in the file that outputs the XML and that you can preview that XML in the browser.

下面是网页的关系的标志,图标,和XML在一起。当页面加载时,负载的函数被调用。该函数设置了地图,然后调用GDownloadUrl。确保您的GDownloadUrl在文件传递,它输出的XML,并且您可以预览该XML在浏览器中。

The full HTML that accomplishes this is shown below (phpsqlajax_map.htm):

完整的HTML来完成,这是如下(phpsqlajax_map.htm)所示:

 


 

 类似资料: