Geo Tips for Javascript

9 views
Skip to first unread message

Greg Tracy

unread,
May 12, 2011, 1:42:34 PM5/12/11
to smsmyb...@googlegroups.com

I've been asked about different ways to use the getnearbystops call using a location provided by the browser. So I'm sharing a snippet of JavaScript code that you can use to get the current location out of the browser using Google's Maps API. 

1. Include the API in your site by referencing the remote JavaScript.

 <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>

2. Call an init function once the page loads. One way to do that (and there are others) is to modify the body tag like so...  <body onload="initialize()">

3. Call the Google API to get the current position, specifying the callbacks when it completes. You'll need to store the lat/long results in a variable somewhere. Once you have it, you can pass it into the getnearbystops call to find all of the nearby stops for the user. It works on the desktop as well as most mobile browsers.


function initialize() {
navigator.geolocation.getCurrentPosition(foundLocation,noLocation);
}

function foundLocation(position) {
// Initialize the current location based on the position
// detected by the browser. We'll use it to center the
// map initially as well as placing a new marker.
var lat = position.coords.latitude;
var lon = position.coords.longitude;
latlng = new google.maps.LatLng(lat,lon);
timeOfLocation = position.timestamp;
}

function noLocation() {
  alert('unable to find a location from the browser');
}


Have fun....
Reply all
Reply to author
Forward
0 new messages