Posts Tagged ‘safari’

With the iPhone 3.0 firmware released today, I thought I’d show you how to access one of the features I’ve been most looking forward to – support for the geolocation API in Safari means I can now create location aware websites.

This will be just a quick demo to retrieve and display the current longitue and latitude of your phone, along with a googlemap so we can see if the results are right.  The more interesting applications will come….

To do this we’ll use javascript and the newly added Navigator.Geolocation interface to call the getCurrentPosition() function to retrieve the current longitude and latitude of the phone, which we’ll display and pass to the googlemaps API.

The code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>iPhone 3.0 geolocation demo</title>
<meta content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" name="viewport"/>
<script>
function handler(location) {
var message = document.getElementById("message");
message.innerHTML ="<img src='http://maps.google.com/staticmap?center=" + location.coords.latitude + "," + location.coords.longitude + "&size=300x200&maptype=hybrid&zoom=16&key=YOURGOOGLEAPIKEY' />";
message.innerHTML+="<p>Longitude: " + location.coords.longitude + "</p>";
message.innerHTML+="<p>Latitude: " + location.coords.latitude + "</p>";
message.innerHTML+="<p>Accuracy: " + location.coords.accuracy + "</p>";
}
navigator.geolocation.getCurrentPosition(handler);
</script>
</head>
<body>
<div id="message">Location unknown</div>
</body>
</html>

The results:

Try it for yourself by pointing your Safari browser at http://bemoko.com/blog/iphonegeo.

Update 27/7/2009: I noticed the zoom level on the google static map API wasn’t being set so the map was zoomed all the way out. I’ve added a default zoom for the demo code above. Not sure if thats a new requirement from Google’s side?