Now that we've written the code to save the user's location at a particular time, we need to consider how we'll display it. In this section, we'll use the Google Maps API to display the user's location right now, as well as recent locations that we've saved for this user.
The Google Maps API is the most popular online mapping API in the world, which is why we will use it for this tutorial. Other mapping APIs are available, including offerings from Microsoft Bing, Nokia, and the open source OpenStreetMap project. My decision to pick the Google Maps API does not reflect on the quality of these other APIs, and you will want to carefully choose between them based on their merits and applicability for your project. I have included links to these projects at the end of this section, as well as to the Google Maps API documentation.
Use of the Google Maps API is free for non-profit websites at the time of writing. Commercial sites are limited to 25,000 map loads per day. Beyond that, you will need to acquire a Google Maps API for Business license by contacting Google directly.
We will be using the Google Maps API v3 for the purposes of this tutorial.
To display our location data, we will use a MySQL function stored in lib.php
to retrieve existing map points. We will also load the Google Maps API using Google's hosted JavaScript library and make use of the following Google Maps objects:
Map
: The Google Map itself
Marker
: An individual point on a Google Map
LatLng
: An object representing a pair of latitude and longitude coordinates
There are three main structural changes we must make to index.php
. First, we must require that lib.php
is loaded. This will give us access to the database and a new function that we'll add to that library.
So far, we've only stored geolocation data; we haven't displayed it to the user at all. However, because we've been saving it to the database, we potentially have a rich history of location data that we can retrieve—organized by both user and time. A new function, getPreviousLocations($user_id)
, returns this data as an array in chronological order using a simple MySQL select call:
Recall that for the purposes of this tutorial, we're always setting $user_id
to 1
. A more sophisticated application would substitute a user identifier from the current browser session, or another location.
By requiring lib.php
at the top of index.php
, we can ensure that we have reliable access to this information from the database:
Another new addition is the JavaScript library that Google provides for the Google Maps API. Note that by omitting the URI scheme (http:
or https:
), we can ensure that the browser will use the correct one, whether your page is accessed over a standard or secure HTTP connection. This is placed within the HTML <head>
tag in index.php
:
Finally, we also need a place on the page to display our map. For this, we establish a new, empty div
element with a unique ID (here I've used map_pane
). The Google Maps API will populate this with a complete map later.
Now that we've set up the framework of the page, we can begin configuring the map. We do this in the JavaScript block at the bottom of the page:
The zoom level for Google Maps starts at 0
, where you can see the entire globe. Theoretically, the zoom levels are infinite, but in practice, for most maps, the maximum level is 19
. Set the zoom level at 15
; it's close enough to be able to view your location with precision, but zoomed out enough to see a large amount of the surrounding neighborhood.
There are a number of different map types at your disposal:
google.maps.MapTypeId.ROADMAP
: The street map view
google.maps.MapTypeId.SATELLITE
: A satellite view of the Earth
google.maps.MapTypeId.HYBRID
: Street map items overlaid on top of the satellite view
google.maps.MapTypeId.TERRAIN
: Terrain information without road markings and so on
For now, set the mapTypeId
to googlemaps.MapTypeId.HYBRID
.
Next, initialize the Map
object with the options you've just defined, and the map_pane
DOM element. This is enough to display the map inside the map_pane
div. We'll save it to the window.googleMap
global variable, which will come in handy.
However, there's every chance we've already got some location information to display. Here's where our PHP function, getPreviousLocations($user_id)
, becomes useful. Recall that it's returning an array of database row objects containing latitude, longitude, and time.
JavaScript is a front-end language, interpreted in the web browser; PHP is a server-side language, interpreted before any HTML is received by the browser. They cannot directly interface with each other. As a result, we need a way to pre-process the array of coordinates so that it's readable by JavaScript. JSON is perfect for this task.
Luckily, PHP provides a very simple function to encode PHP variables as JSON: json_encode
. We just need to use this on the result of getPreviousLocations($user_id)
. Remembering that we're hardcoding the value 1
in place of $user_id
, our hybrid JavaScript/PHP code looks like the following:
If there was a single location point in the database, this might be rendered as follows:
In other words, jsonPoints
is seen by JavaScript as an array of JavaScript objects. We can simply check that the array is non-empty, and iterate through any elements using the Array.forEach
method:
We establish window.points
as a global JavaScript array of Marker objects, the objects used to represent individual geographic points in the Google Maps API. On instantiation, Marker objects are given a position in terms of a LatLng object containing latitude and longitude, and a reference to the Google Map that will display them. (We can simply supply the window.googleMap
variable we created earlier for this purpose.)
Once the previously saved geographic points have been written to the map, we must ensure that the newly detected location, if it has been successfully obtained, is also added.
Previously, we had written a message to the screen—Location saved
—once a location had been successfully processed. Now, we need to also draw it to the map.
First, we create a new LatLng object containing the latitude and longitude of the newly saved location:
Next, we can center the map on it using the Map object's setCenter
method:
Finally, we create a new Marker object, containing a simple title, the newly created LatLng object, and a reference to our Map:
The location appears as a pin on the map, alongside previously saved locations.