I'm using the following script and having difficulty passing in the lat and lon variables I created with user's location. When I remove the lat and lon variables I created and manually put in 0,0 it works fine for debugging's sake...The map should be displayed in a div with id of map_canvas.
$(document).ready(function() {
navigator.geolocation.getCurrentPosition(handle_geolocation_query,handle_errors);
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var latlng = new google.maps.LatLng(lat, lon);
var myOptions = {
zoom: 1,
center: latlng,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions); map.setTilt(45);
});
Your problem is probably right here:
navigator.geolocation.getCurrentPosition(handle_geolocation_query, handle_errors);
Presumably, handle_geolocation_query
looks something like this:
var position;
function handle_geolocation_query(pos) {
position = pos;
}
But navigator.geolocation.getCurrentPosition
is an asynchronous function call:
The
getCurrentPosition()
method takes one, two or three arguments. When called, it must immediately return and then asynchronously attempt to obtain the current location of the device. If the attempt is successful, thesuccessCallback
must be invoked [...]
Emphasis mine.
So, your handle_geolocation_query
callback will be called by getCurrentPosition
when it has the position, not when you call getCurrentPosition
. So, when you get to here:
var lat = position.coords.latitude;
var lon = position.coords.longitude;
Your position
won't necessarily contain anything useful and you probably get an error telling you that position.coords
is undefined or not an object or something similar.
You need to move your new google.maps.LatLng
and new google.maps.Map
stuff to inside the handle_geolocation_query
callback where you'll have a useful position
value.