Monday, June 22, 2009

iPhone GeoLocation in Safari

iPhone GeoLocation in Safari uses the Safari’s new geoLocation api to retrieve the current location and in turn gets address information using Google Maps geoCoding api.

photo

var geocoder;

function initialize() 
{
    geocoder = new GClientGeocoder();
    findLocation();
}

function findLocation()
{
    if (navigator.geolocation != null)
        navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
    else
        document.getElementById("map_canvas").innerHTML  = 'Browser does not support geoCoding';
}

function foundLocation(position)
{
    getAddress(new GLatLng(position.coords.latitude,position.coords.longitude));
}

function noLocation()
{
    document.getElementById("map_canvas").innerHTML  = 'Could not find location';
}
 
function getAddress(latlng) 
{
  if (latlng != null) 
  {
    geocoder.getLocations(latlng, showAddress);
  }
}

function showAddress(response) {
  if (!response || response.Status.code != 200) {
    alert("Status Code:" + response.Status.code);
  } 
  else 
  {
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
    var locData = 
    '<b>latlng:</b>' + place.Point.coordinates[1] + "," + place.Point.coordinates[0] + '<br>' +
    '<b>Status Code:</b>' + response.Status.code + '<br>' +
    '<b>Status Request:</b>' + response.Status.request + '<br>' +
    '<b>Address:</b>' + place.address + '<br>' +
    '<b>Accuracy:</b>' + place.AddressDetails.Accuracy + '<br>' +
    '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode;
    document.getElementById("map_canvas").innerHTML  = locData;
  }
}

No comments: