Check out my NEW training website for front-end web developers, FrontendMasters.com

HTML5 Geolocation with Fallback to Google Ajax API

April 12, 2010

Google Ajax API does location lookup, so it makes it a great fallback for the native HTML5 Gelocation API. Of course, the fallback will never get near the same accuracy as GPS lookup, because it does a lookup on your ISP, but it is at least able to get you in the ballpark as a fallback.

Include Google AJAX API with your api key and then go ahead and use this code.

<script src="http://www.google.com/jsapi?key=YOUR_API_KEY"></script>
<script>
var myLocation; // global variable to store lat/lng
if (navigator && navigator.geolocation) {
// HTML5 GeoLocation
function getLocation(position) {
myLocation = {
"lat": position.coords.latitude,
"lng": position.coords.longitude
}
}
navigator.geolocation.getCurrentPosition(getLocation);
} else {
// Google AJAX API fallback GeoLocation
if ((typeof google == ‘object’) && google.loader && google.loader.ClientLocation) {
myLocation = {
"lat": google.loader.ClientLocation.latitude,
"lng": google.loader.ClientLocation.longitude
}
}
}</script>

You then have access to the user’s location with the "myLocation" variable and can take it from there.

Like this article? You'll like my NEW training website for front-end web developers!

Video workshops on jQuery, JavaScript, HTML5, web performance and more.
Upgrade your front-end developer skills!

15 comments

#1. Erik on April 13, 2010

Very nice..

Wouldn’t it be more correct to include the google api script only if the native geolocation wouldn’t work?

Cheers, and thanks for a great example..

#2. Marc Grabanski on April 13, 2010

Erik: Maybe, but I use the Google Ajax API to load jQuery and Google Maps anyways so that is why I didn’t bother including it only inside the fallback section.

#3. Dan on April 16, 2010

Thanks for this- I was hoping the usage was as simple as it seemed based on a quick read of the API. Your example gives me quite a bit of encouragement.

#4. kevin on April 27, 2010

Thanks for the brief article Marc. I can’t wait for Google’s API 3 with the inclusion of bike paths… I’m on a bike and…

#5. theo on April 29, 2010

i keep getting undefined any idea?

#6. BuriB on June 30, 2010

hi there.

How can I check if user accepted the geolocation check or not?
I’d like to initialize a map, then navigate to the myLocation coordinates.

#7. Marc Grabanski on June 30, 2010

The navigator.geolocation.getCurrentPosition(success, error) takes two functions, success and error. You can branch the code further by changing the above code to navigator.geolocation.getCurrentPosition(getLocation, error); and making a new function error() { ... } to handle the case where someone denies sharing their location.

#8. BuriB on June 30, 2010

solved my problem.

thanks!

#9. Corey on July 09, 2010

I just ran across you blog today. I must say it is a nice resource so far. I just finished reading your ‘how to be a great web developer’ and it’s nice to know I am going about it in the right way; I just started up a blog myself.

In fact, one of my first posts was using the Google API with C#:
http://offbyone.us:8888/?p=171

Super easy and fun.

Kinda wish I had found you before I wrote it, though. Then again, I probably would have been bugging you instead of troubleshooting until I found out about if (!IsPostBack) and the ASP.NET page life cycle.

#10. Corey on July 09, 2010

By the way, let me add two things.

First, I know you are an open source guy; I wouldn’t have asked you about .net. I am also and learning to use jQuery and that is why I ran across your blog.

And secondly, I wish there were a way to have two different gravitar icons available to me with my main email address. Having my WoW toon show up next to my post has to detract something from my statements. I am off to add an email and icon to gravitar.

Anywho wtb edit button.

#11. Corey on July 09, 2010

Now that I have mad an idiot of myself. Thanks again for your blog.

#12. tanweer on August 12, 2010

Hi every One

try this is is very simple

 Dim ipAddress As String = "202.147.177.132"
Dim req As WebRequest = WebRequest.Create("http://ipinfodb.com/ip_query.php?ip=" & ipAddress)
Dim resp As WebResponse = req.GetResponse()
Dim s As Stream = resp.GetResponseStream()
Dim sr As StreamReader = New StreamReader(s, Encoding.ASCII)
Dim doc As String = sr.ReadToEnd() ’ get text to a string
Dim length As Integer = doc.Length – 1
Dim startInd As Integer = doc.IndexOf("<CountryCode>") + 13
doc = doc.Substring(startInd)
length = doc.Length – 1
Dim tagStart As Integer = doc.IndexOf("<")
Dim code As String = doc.Remove(tagStart, length – tagStart)
startInd = doc.IndexOf("<CountryName>") + 13
doc = doc.Substring(startInd)
length = doc.Length – 1
tagStart = doc.IndexOf("<")
Dim Country As String = doc.Remove(tagStart, length – tagStart)
startInd = doc.IndexOf("<RegionName>") + 12
doc = doc.Substring(startInd)
length = doc.Length – 1
tagStart = doc.IndexOf("<")
Dim RegionName As String = doc.Remove(tagStart, length – tagStart)
startInd = doc.IndexOf("<City>") + 6
doc = doc.Substring(startInd)
length = doc.Length – 1
tagStart = doc.IndexOf("<")
Dim City As String = doc.Remove(tagStart, length – tagStart)
startInd = doc.IndexOf("<ZipPostalCode>") + 15
doc = doc.Substring(startInd)
length = doc.Length – 1
tagStart = doc.IndexOf("<")
Dim ZipCode As String = doc.Remove(tagStart, length – tagStart)
startInd = doc.IndexOf("<Latitude>") + 10
doc = doc.Substring(startInd)
length = doc.Length – 1
tagStart = doc.IndexOf("<")
Dim Latitude As String = doc.Remove(tagStart, length – tagStart)
startInd = doc.IndexOf("<Longitude>") + 11
doc = doc.Substring(startInd)
length = doc.Length – 1
tagStart = doc.IndexOf("<")
Dim Longitude As String = doc.Remove(tagStart, length – tagStart)
#13. Beben Koben on November 25, 2010

i don’t understand about script, btw i found script like this, maybe usefully…thanks^^
<script type="text/javascript">
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} else {
alert('Geolocation Not Support');
}

function successFunction(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
alert('Latitude:'lat' Longitude:'+long);
document.write (lat);
document.write (long);
}

function errorFunction(position) {
alert('Error!');
}
</script>

#14. Beben Koben on November 25, 2010

ones more…for completely…xixixi
http://goo.gl/b3eVp

#15. NewUser on April 17, 2013

Tell me please, this code work with GPS navigator or he working only with IPlocation? And where can I see then this location? In my api account or In access log file In hosting? I dont understent about that. I can see this information fallback on the map or text with latitude and longitude?

Leave a comment

Comment in textile images by gravatar