In this example, I try to explain you how to embed custom markers, containing data from an external datasource (in this case a MySQL database) in a Google Maps map, like the example below:
To test my code yourself, you need the following:
- A Google Maps API key (get one here)
- A Webserver capable of running PHP and MySQL (for development I recommend XAMPP)
- Little knowledge of PHP and JavaScript
Lets call the project MapSomeStuff.
The whole thing consists of two files, a JavaScript file, wich contains the most of the calls to the Google Maps API and a PHP file, containing my MapSomeStuff class wich gets data from the database and prepares it to be put on the map.
Technical backgrounds
In a first step, we take the address of our marker- entry and pass it over to the Google Maps API to translate it to latitudinal and longitudinal (lat and lng) coordinates (wich is essential in the next step).
Now the data, wich is later displayed on the map as a marker is being read from the database and formated as XML- output (look out for the lat and lng attributes):
<markers> <marker name="Basel SBB" street="Centralbahnplatz" nr="1" town="Basel" zip="4051" country="Switzerland" description="Railwaystation Basel SBB" lat="47.5482662" lng="7.5909349"/> </markers>
In my example we still have the address in the XML dataset. This is only additional information for the user. In fact, Google Maps only needs the lat and lng attributes to place the marker on the map.
The XML gets sent to the Google Maps API, wich then places the markers on the correct coordinates.
The code
To avoid ruining the site’s look, I link the code. Just downlad the file, rename accordingly and put them all in the same directory:
mapsomestuffphp – containing the PHP class and HTML parts. Rename to mapsomestuff.php
mapsomestuffjs – containing the API calls. Rename to mapsomestuff.js
mapsomestuffsql – containing the database structure and an initial dataset