How to Create XML for Google Maps
In a Google Maps application, it is common for the data plotted on the map to reside in a database somewhere on the Internet. One of the ways to feed that data to Google Maps is to create and send an Extensible Markup Language (XML) dataset upon request from an Asynchronous JavaScript and XML (AJAX) call. To create the XML for Google Maps, use PHP to access data in the database, build a well-formed XML string as you iterate through the data points and echo the result to send it back with the Google Maps AJAX call.
Instructions
-
-
1
Outline the structure of the XML that will be sent to Google Maps. For example, you might create an XML file of U.S. cities with their location and the current temperature, similar to the following:
<cities>
<city>
<name>Atlanta</name>
<latitude>33.65</latitude>
<longitude>-84.42</longitude>
<temperature>78</temperature>
</city>
<city>
<name>Boston</name>
<latitude>42.37</latitude>
<longitude>-71.03</longitude>
<temperature>56</temperature>
</city>
...
</cities> -
2
Use a text editor such as Notepad to create a new PHP program file that will create the XML for Google Maps on demand. Designate a password to be sent with the request for the XML data as a security precaution. Check for the existence of the password and for the correct password value. Exit the program quietly if the correct password was not provided. Type:
<?php
$secret = isset($_REQUEST['secret']) ? $_REQUEST['secret'] : null;
if (!$secret || $secret !== "XMLRequest") die(); -
-
3
Open a connection to a MySQL database server and select the database with the data that will be used to create the XML for Google Maps. Check that the database server connection and database selection were successful. Exit with an error message if either function fails. Type:
$dbc = mysql_connect("localhost", "username", "password") or die("Error connecting to database server");
$db = mysql_select_db("database") or die("Error selecting database!"); -
4
Initialize a string that will contain the XML data to be sent to Google Maps. Begin the string with an XML header and the opening tag of the root element. Type:
$xml = '<?xml version="1.0" encoding="utf-8" standalone="yes">';
$xml .= "<cities>"; -
5
Create and execute a query on the database to return the data points for the XML. Iterate through the results and add elements to the XML string according to the layout you established. Type:
$query = "SELECT * FROM datapoints";
$result = mysql_query($query);
while (($row = mysql_fetch_assoc($result))) {
$xml .= "<city><name>".$row["city"]."</name><longitude>".$row["longitude"]."</longitude><latitude>".$row["latitude"]."</latitude><temperature>".$row["temperature"]."</temperature></city>";
} -
6
Close the root tag on the XML string and echo it to pass it to a Google Maps AJAX call to the PHP program. Type:
$xml .= "</cities>";
echo $xml;
?>
-
1