9lessons programming blog
Loading Search
9lessons Bring Friends
Wall Script
Follow Me:
Tuesday, June 7, 2011

Geo Location with HTML5 and Jquery

Last few days I have been working with HTML5 elements, it’s very interesting. This post explains you how to get geo location latitude and longitude values using Jquery. I found a geocode location script from html5demos.com and I have customized bit of code. It is useful you can built foursquare kind of location check out web application.

Geo Location with Jquery

Live Demo     Mobile Live Demo

JavaScript code
Contains Google Map + HTML5 code. Using jquery cookie plugin storing latitude an longitude values $("#check").click(function(){})- check is the ID name of Check-out button.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/
1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript">
function success(position)
{
var s = document.querySelector('#status');
if (s.className == 'success')
{
return;
}
s.innerHTML = "Found you!";
s.className = 'Success';
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcanvas';
mapcanvas.style.height = '100%';
mapcanvas.style.width = '100%';
document.querySelector('#map').appendChild(mapcanvas);
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeControl: false,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"You are here!"
});
$.cookie("MyLat", position.coords.latitude); // Storing latitude value
$.cookie("MyLon", position.coords.longitude); // Storing longitude value
}
function error(msg)
{
var s = document.querySelector('#status');
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'Fail';
}
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(success, error);
}
else
{
error('Not supported'); //HTML Support
}

//Jquery Code
$(document).ready(function()
{
$("#check").click(function()
{
var lat = $.cookie("MyLat");
var lon = $.cookie("MyLon");
alert('Latitued: '+lat);
alert('Longitude: '+lon);
var url="http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=false";
alert('Google Map API: '+url);
//Get Json Request Here
});
});
</script>
//HTML Code
<input type='button' id='check' value='Check-out'/>
<div id="status">Loading.............</div>
<div id="map"></div<

Google Geocoding API allowing 2,500 geolocation requests per day so that I dropped Google map JSON parsing with jquery. (Google Maps API Premier allows 100,000 requests per day.)
Comments
{ 55 comments }
Debajyoti Das said...

From the PC it shows the city...

If I view the page with a GPS enabled mobile... will it show the exact location.

Srinivas Tamada said...

@Debajyoti

Yes It will..

codingplayground said...

a related example:

http://www.headtagger.com/lesie2/map.html

Anonymous said...

would there be a request limit ... if you just want to get the lat and lon position?

Anonymous said...

From Xperia Arc (Android 2.3.3) it only says failed.

Anonymous said...

Good Tutorial !

Sandeep said...

Hi Srinivas

map not displaying in demo only showing Loading...

Srinivas Tamada said...

HTML5 supports Chrome and Firefox latest versions.

Ivan said...

Hello,
On a PC (Firefox 4) I get some alerts: "Latidude:null", "Longitude:null" and "Google Map API: http://maps.googleapis.com/maps/api/geocode/json?latlng=null,null&sensor=false"
On iPhone 4 I get two "null" alerts
Any clue? Thanks...

Anonymous said...

not found in chrome... faild.

No me funciono en Chrome, y tengo la ultima version.

dungfit said...

good application

Srinivas Tamada said...

@Ivan

Problem with jquery.cookie.js plugin

Ivan said...

Hi Srinivas, is it a problem of mine? Should I delete the cookies?

Junior Santos said...

HTML5 Geolocation isnt work on iPhone. Andd on Safari Mac just if you have a wireless connection.

chooey said...

thanks, that a good tutorial

Anonymous said...

Awesome

Anonymous said...

Hi,

Live demo is not working properly.

Its showing failed message.

Ramji

joomla developer said...

Nice but how do i add it to my blog.

Anonymous said...

You also can use this plugin http://gmap3.net

It manages both JQuery and geo-localisation

Beben Koben said...

hihihi...
<div id="map"></div<
hehehe...<

Sage said...

Success: On the PC - Firefox 4, running the demo, I get a top bar that asks to "share location". After clicking the button, the demo pops up the Google Map and finds my exact location (Very Cool!) and I can pull up the Long/Latt.

Fail: If viewing the Mobile Demo on my iPhone, I see the check out box but nothing happens, just get the two null popup boxes.

Srinivas Tamada said...

@Sage

Enable your browsers cookie storing option

farzin said...

demo is working fine in firefox 3.5
it shows my exact location!!

CelLo said...

Thank you, so I need it for work.

satyanarayana panchala said...

hi srinivas,
You said that Google not allowing 2500 API requests in a day.But Using JSON Is also any limit in using Google Map?

Please give ...

tareq said...

you are such a life saver. thanks for this. i was searching for this kind of tuts. actually i was trying to load the whole database to get the geo location... it was boring.. thanks again. nice tuts.

ny2244111 said...

Good stuff Srinivas. Can you point me to the documentation which states Google only allows 2500 geolocation requests per client? I found the documentation which talks about 2500 geocoding requests per IP but i've been searching for hours for request limit documentation on geolocation. I know the operation must be expensive on their end but I can't see how they can restrict something like that when it's built into the HTML5 spec.

TrustWeb said...

good tutorial, i was looking for that!

Anonymous said...

Nice but it dont work with internet explorer

Anonymous said...

Good tutorial. It works with FF and Chrome. De mobile version doesn't work on mij iPhone 3GS and Blackberry 9800 Torch

moso said...

good

Prashant said...

Nice but not accurate

Anonymous said...

thanks this is what I was looking for. :D

Silvi said...

not accurate if using wifi

Anonymous said...

nice

Adewale George said...

only shows loading

Anonymous said...

working on my IPhone!

Is this app will support on all mobile phone with gps enabled?

Tobaonline.com said...

I try import gmail using you'r source, why result??
Server error
The website encountered an error while retrieving. It may be down for maintenance or configured incorrectly.
Here are some suggestions:
Reload this webpage later.
HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.

Any body help me?? Is need adding configuration on php.ini in server hosting??

Thanks before.

Anonymous said...

it says $.cookie is not a function

vrushali said...

hiiiiiiiiiii im nt geeting the latitude longitude on clicking on check out.ipasted the same code above is there any changes ..im new to jquery plz do reply fast

Anonymous said...

Hi, Is it possible to make this into a store locator. The list could be pulled from a xml file or something.

naxis said...

How can I put more markers?
Thank you

Anonymous said...

Hi!
How do I save location in a database?

Joomla development services said...

Awesome application, I am new to use and i like it very much..

Thanks for this.

dian said...

can u show me how to using jquery mobile + html5 to show Open Street Map

tanks before

Anonymous said...

can this source code auto detect location and display place nearest

bobit said...

well explained
expecting more examples

All About Digital Marketing said...

Great Scrip thanks for the Share Srinivas :)

Anonymous said...

Useful Hacks...Thumbs Up!!!

Anonymous said...

Hi srinivas. I tried same code but i am not getting the out put .I am getting Failed,latitude :null,logitude: null.I am new to this ,please let me konw why I am not getting the output and what are the software and hardware requirement for testing this program in pc and mobile(I used windows 7,firefox 8) and mobile device(android samsung galaxy s3 mini,firefox)
Please help me

S.PremKumar said...

how to find my destination location latitude and longitude from my latitude longitude

Anonymous said...

hi everybody! Tell me please, exmple when some user load webpage then where can I see geopositin this user which came on my website?

Anonymous said...

Please answer me somebody. I put this code on my website, all work but where can I take or see then this cookie? Where I should look this cookies? Please help me!

Anonymous said...

can it be possible to save current location to some server.. periodically

Mamun said...

hi, how to find my destination location latitude and longitude from my latitude longitude, Anyway Thanks for anther Quality Tutorials

Post a Comment